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

React Vite项目中Tailwind CSS使用Google Fonts失效求助

问题描述

React+Vite项目已配置Tailwind CSS,尝试引入Google Fonts的Inter字体但始终无法生效。以下是相关配置文件:

index.css

@import url('https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap');

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

tailwind.config.js

/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {
      fontFamily: {
        inter: ["Inter", "sans-serif"],
      }
    },
  },
  plugins: [],
}

index.html

<!doctype html>
<html lang="en">
  <head>
    ...
  </head>
  <body>
    <div id="root"></div>
    <script src="https://cdn.tailwindcss.com"></script>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import tailwindcss from 'tailwindcss'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  css: {
    postcss: {
      plugins: [tailwindcss()],
    },
  }
})

postcss.config.js

export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

排查与解决办法

1. 移除冲突的Tailwind CDN引入

你的index.html中同时引入了CDN版Tailwind和本地PostCSS配置的Tailwind,两者会发生样式优先级冲突,直接导致自定义字体配置失效。删除这一行即可:

<script src="https://cdn.tailwindcss.com"></script>

2. 确保字体正确应用

  • 全局默认字体:如果想让整个项目默认使用Inter,修改tailwind.config.js,将Inter设为默认无衬线字体:
    theme: {
      // 替换默认sans字体族
      fontFamily: {
        sans: ["Inter", "sans-serif"],
      },
      extend: {},
    }
    
  • 局部使用字体:如果只需要在特定组件中使用,保持原tailwind.config.js的配置,在组件中添加font-inter类:
    <h1 className="font-inter text-2xl">使用Inter字体的标题</h1>
    

3. 验证与生效

  • 重启Vite开发服务器,确保配置变更生效。
  • 打开浏览器开发者工具,检查元素的font-family样式是否包含Inter;同时在「网络」标签确认Google Fonts的请求已成功加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:58:24