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

NextJS+TailwindCSS项目报错:无法识别font-extrabold工具类

解决Next.js + Tailwind CSS中font-extrabold未知工具类错误

问题重现

项目运行时抛出错误:

Error evaluating Node.js code
Error: Cannot apply unknown utility class: font-extrabold

自定义工具类中使用font-extrabold无法被Tailwind识别,已加载本地WorkSans字体并配置Tailwind内容目录,但问题仍存在。

核心问题排查

从提供的代码看,存在两个关键配置错误:

  1. 字体权重映射错误,导致Tailwind无法匹配对应字体权重
  2. 未在Tailwind主题中注册自定义字体,使得权重类无法关联加载的字体

解决方案步骤

1. 修正字体权重映射

在app/layout.tsx的localFont配置中,修正字体文件与权重的对应关系(Regular对应400,Medium对应500,补充Light的300权重):

const workSans = localFont({
  src: [
    { path: './fonts/WorkSans-Black.ttf', weight: '900', style: 'normal' },
    { path: './fonts/WorkSans-ExtraBold.ttf', weight: '800', style: 'normal' },
    { path: './fonts/WorkSans-Bold.ttf', weight: '700', style: 'normal' },
    { path: './fonts/WorkSans-SemiBold.ttf', weight: '600', style: 'normal' },
    { path: './fonts/WorkSans-Medium.ttf', weight: '500', style: 'normal' },
    { path: './fonts/WorkSans-Regular.ttf', weight: '400', style: 'normal' },
    { path: './fonts/WorkSans-Light.ttf', weight: '300', style: 'normal' },
    { path: './fonts/WorkSans-ExtraLight.ttf', weight: '200', style: 'normal' },
    { path: './fonts/WorkSans-Thin.ttf', weight: '100', style: 'normal' },
  ],
  variable: '--font-work-sans',
});

2. 在Tailwind配置中注册自定义字体

修改tailwind.config.ts,在theme.extend中添加自定义字体族,关联加载的字体变量:

import type { Config } from 'tailwindcss';

const config: Config = {
  darkMode: ["class"],
  content: [
    './pages/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',
    './app/**/*.{js,ts,jsx,tsx,mdx}',
    './sanity/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    extend: {
      fontFamily: {
        'work-sans': ['var(--font-work-sans)', 'sans-serif'],
      },
    },
  },
  plugins: [],
};

export default config;

3. 在根布局中应用字体

在app/layout.tsx的根元素上,添加字体变量和字体类,确保全局生效:

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en" className={`${workSans.variable} font-work-sans`}>
      <body>{children}</body>
    </html>
  );
}

4. 验证自定义工具类

此时globals.css中的自定义工具类可正常识别font-extrabold:

@layer utilities {
  .text-30-extrabold {
    @apply text-[30px] font-extrabold text-white;
  }
}

额外排查点

  • 重启Next.js开发服务器,确保配置变更生效
  • 确认globals.css已在根布局中正确导入(默认Next.js会自动处理)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 22:47:12