Twind中使用@import及@font-face引入自定义字体不生效如何解决
Twind自定义字体配置不生效修复方案
你的配置存在4个核心问题,逐一修正后字体即可正常加载:
核心错误点
- 谷歌字体引入链接拼写错误:你写的链接参数是
?amily=,缺少首字母f,正确参数为?family=;且@import规则不能放在preflight配置项中,preflight仅用于注入基础样式重置规则,@import必须放在所有CSS规则最前,Twind中需要通过全局样式配置项声明。 - 本地字体访问路径错误:如果是Fresh等约定static为静态资源根目录的框架,
static/fonts/下的文件对外访问路径为/fonts/xxx,你配置的/static/fonts/xxx路径会返回404,无法加载字体文件。 - @font-face配置格式错误:Twind preflight不支持数组形式的@font-face传参,需要拼接为合法CSS字符串;且ttf字体对应的format值为
truetype,你写的ttf是无效值。 - Twind初始化逻辑错误:加了
IS_BROWSER判断会导致服务端渲染时Twind未初始化,类名生成、样式注入逻辑异常。
修正后配置代码
twind.ts
import { Configuration, setup } from "twind"; export * from "twind"; export const config: Configuration = { darkMode: "class", mode: "silent", theme: { extend: { fontFamily: { custom1: ['Roboto','sans-serif'], custom2: 'Organo', custom3: 'Varela' }, spacing: { 128: '32rem', 144: '36rem', }, }, }, // 全局样式放最前,@import写在这里 global: { '@import': `url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,400;0,700;1,400&display=swap')`, }, preflight: { // @font-face 以合法CSS字符串形式声明,修正路径和format值 '@font-face': ` @font-face { font-family: 'Organo'; font-weight: 400; src: url('/fonts/Organo.woff') format('woff'); font-display: swap; } @font-face { font-family: 'Varela'; font-weight: 400; src: url('/fonts/VarelaRound-Regular.ttf') format('truetype'); font-display: swap; } ` }, }; // 移除浏览器判断,服务端、客户端都要初始化 setup(config);
组件使用(原有写法无需修改)
/** @jsx h */ /** @jsxFrag Fragment */ import { Fragment, h } from "preact"; import { tw } from "@twind"; export default function Home() { return ( <> <div class={tw`flex flex-col min-h-screen`}> <p class={tw`my-6 text(4xl sm:4xl md:4xl) font-custom1`}> hello, world </p> {/* 其余自定义字体直接用font-custom2、font-custom3即可 */} </div> </> ); }
验证步骤
- 启动项目后打开浏览器控制台,切换到网络面板筛选字体类请求,确认Roboto、Organo、Varela三个字体请求都返回200,无404报错
- 选中对应DOM元素,在计算样式面板查看
font-family值是否匹配你配置的字体,是否被其他样式覆盖
内容的提问来源于stack exchange,提问作者dev3
相关产品推荐
相关产品推荐

