我正在尝试在我的 React 项目中使用 Vite 和 Tailwind CSS v4 自定义字体 (RetroGaming.ttf),但该字体无法应用。该@font-face
规则似乎被忽略了,生成的 Tailwind 类的属性中不包含该自定义字体font-family
。
技术栈
- 框架: React(^19.0.0)
- 构建工具: Vite(^6.2.0)
- 样式: Tailwind CSS(^4.1.3)
- CSS 处理: PostCSS (^8.5.3)
autoprefixer
与@tailwindcss/postcss
- 字体文件: [RetroGaming.ttf]
目标
定义RetroGamingFont
via@font-face
并使用 Tailwind 实用程序类应用它font-custom-retro
。
问题
- 自定义字体不会呈现;元素使用后备字体。
- 生产的CSS包(
dist/assets/
)缺少@font-face
规则。 - 生成的
.font-custom-retro
类仅包含后备字体(sans-serif
),而不是RetroGamingFont
。 - 浏览器开发工具未显示[/fonts/RetroGaming.ttf] 的404 错误
@font-face
无论是在 中src/index.css
还是直接在 中,问题仍然存在index.html
。
配置
tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {
fontFamily: {
'custom-retro': ['RetroGamingFont', 'sans-serif'], // Font definition with fallback
},
},
},
plugins: [],
}
postcss.config.js
export default {
plugins: {
'@tailwindcss/postcss': {}, // Required for v4
autoprefixer: {},
},
}
src/index.css(目前为空@font-face
)
@import "tailwindcss"; /* Tailwind v4 import, placed first */
/* @font-face moved to index.html for testing */
index.html(当前状态)
<!-- Inside <head> -->
<style>
@font-face {
font-family: 'RetroGamingFont';
src: url('/fonts/RetroGaming.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
</style>
CompatibilityForm.jsx中的用法
<h2 className="text-2xl font-custom-retro text-pink-400">...</h2>
<label className="font-custom-retro text-indigo-200">...</label>
我尝试过的方法
正确的 Tailwind v4 设置:
- 使用
@import "tailwindcss";
src/index.css
- 使用
@tailwindcss/postcss
插件,无需@tailwindcss/vite
插件。
@font-face
放置:
src/index.css
在(之后)中尝试过@import
并直接在index.html
<style>
标签中尝试过。
两者都不起作用。
文件路径验证:
- 确认公共资产
public/fonts/RetroGaming.ttf
存在且/fonts/RetroGaming.ttf
路径正确。
字体名称:
- 简化为
RetroGamingFont
(无空格)。
开发工具检查:
- 已验证的
.font-custom-retro
类已应用,但计算font-family
使用了后备。 - 字体文件没有网络错误。
问题
为什么 Tailwind CSS v4 / PostCSS / Vite 无法正确处理或识别该@font-face
规则,导致自定义字体无法包含在font-family
实用程序类的定义中?我是否遗漏了 Tailwind v4 和 Vite 中自定义字体的具体配置步骤?
CSS-first 配置(推荐)
从 TailwindCSS v4 开始,tailwind.config.js 已停止使用。取而代之的是 CSS-first 配置方法。在 CSS-first 配置中,您可以使用
@theme
指令自定义设置。为此,有各种命名空间可用。注意:在这种情况下,
tailwind.config.js
可以删除该文件。@theme
指令- TailwindCSS v4 文档使用
--font-*
命名空间,您可以声明字体。旧版基于 JavaScript 的配置
或者,您仍然可以
tailwind.config.js
通过@config
指令使用。@config
指令- TailwindCSS v4 文档./src/index.css
tailwind.config.js
注意:在这种情况下,无需声明
content
属性。TailwindCSS v4 带有自动源检测功能。v4 tailwind 不使用配置中的样式,您需要直接在 css 文件中创建样式并创建变量。
您可以在 HTML 中使用该字体: