You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tailwind CSS v4+Vite+React自定义@font-face字体失效求助

在Vite+Tailwind CSS v4的React项目中自定义字体不生效问题

技术栈

  • 框架:React (^19.0.0)
  • 构建工具:Vite (^6.2.0)
  • 样式方案:Tailwind CSS (^4.1.3)
  • CSS处理:PostCSS (^8.5.3) 搭配autoprefixer和@tailwindcss/postcss
  • 字体文件:RetroGaming.ttf

目标

通过@font-face定义名为RetroGamingFont的自定义字体,并通过Tailwind工具类font-custom-retro在组件中应用。

问题现象

  1. 自定义字体未渲染,元素仅显示后备字体sans-serif
  2. 生产环境打包后的CSS文件(dist/assets/)中缺失@font-face规则
  3. 生成的.font-custom-retro工具类仅包含后备字体,未加入RetroGamingFont
  4. 浏览器开发者工具显示字体文件/fonts/RetroGaming.ttf无404错误,路径正常
  5. 无论将@font-face放在src/index.css还是index.html的<style>标签中,问题均存在

现有配置

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'],
      },
    },
  },
  plugins: [],
}

postcss.config.js

export default {
  plugins: {
    '@tailwindcss/postcss': {}, // Tailwind v4必需配置
    autoprefixer: {},
  },
}

src/index.css

@import "tailwindcss"; /* Tailwind v4标准导入方式,置于文件最前 */
    
/* 曾在此处添加@font-face规则,后移至index.html测试 */

index.html(当前状态)

<!-- <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官方要求配置:在src/index.css中使用@import "tailwindcss";,使用@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配置自定义字体是否存在遗漏的关键步骤?


内容的提问来源于stack exchange,提问作者Paul Martinez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 09:37:20