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

React+TailwindCSS项目中自定义字体无法加载问题求助

React + TailwindCSS 自定义字体className不生效问题排查与解决

问题详情

基于React JS和TailwindCSS开发的应用,所有Tailwind属性正常生效,但自定义字体无法通过font-body这类className加载。直接用style属性设置字体时,显示正常。

相关代码

页面组件代码

<div className="flex flex-row mr-8">
  <p className="text-white font-bold font-body">
    SALE ESPORTS
  </p>
</div>

tailwind.config.js 配置

module.exports = {
  content: ["./src/**/*.{html, js, ts, jsx, tsx}"],
  theme: {
    fontFamily: {
      body: ["Chakra Petch"],
      gaming: ["Press Start 2P"],
      icons: ["Material Icons"],
    },
    extend: {
      colors: {
        primary: {
          accent: "#30ACFF",
          main: "#4448BB",
          dark: "#000A3B",
        },
        secondary: {
          accent: "#E84AE6",
          main: "#C01EE1",
          dark: "#70288F",
        },
        backColor: "#1A1B1F",
      },
    },
  },
  plugins: [],
};

index.css 样式文件

@tailwind base;
@tailwind components;
@tailwind utilities;

index.html 字体引入

<link
  href="https://fonts.googleapis.com/css2?family=Chakra+Petch&display=swap"
  rel="stylesheet"
/>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link href="/dist/output.css" rel="stylesheet" />

项目结构

根目录包含dist、node_modules、src文件夹,以及index.html、package.json、tailwind.config.js等核心配置文件。


解决步骤

1. 调整字体引入顺序

把preconnect前置,优化字体加载优先级,避免因加载顺序导致字体未就绪:

<link rel="preconnect" href="https://fonts.googleapis.com" />
<link
  href="https://fonts.googleapis.com/css2?family=Chakra+Petch&display=swap"
  rel="stylesheet"
/>
<link href="/dist/output.css" rel="stylesheet" />

2. 补充字体fallback(推荐)

在Tailwind配置中添加系统字体作为备选,确保字体加载失败时仍有良好显示:

fontFamily: {
  body: ["Chakra Petch", "sans-serif"],
  gaming: ["Press Start 2P", "monospace"],
  icons: ["Material Icons"],
},

3. 验证Tailwind是否生成对应字体类

打开dist/output.css,查找.font-body类,确认存在类似以下的代码:

.font-body {
  font-family: Chakra Petch, sans-serif;
}

如果不存在,检查tailwind.config.js的content路径是否正确——确保使用font-body的组件在src目录下,且文件后缀匹配配置的{html, js, ts, jsx, tsx}类型。

4. 清除缓存并重新构建

执行构建命令更新样式,开发环境重启服务器:

# npm
npm run build

# yarn
yarn build

5. 排查样式冲突

通过浏览器开发者工具查看元素的计算样式,确认font-family是否被其他CSS规则覆盖。如果存在冲突,可通过增加样式优先级(如添加父级选择器)或调整样式加载顺序解决。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:47:21