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

NextJS中多Google Web字体加载异常问题求助

Next.js 多Google Web字体加载异常问题排查

我在Next.js应用中加载多款Google Web字体时遇到问题,已参照官方文档操作,但测试标题仍显示为Roboto字体。以下是我的代码配置:

字体定义文件(fonts.ts)

import { Inter, Heebo } from "next/font/google";

export const inter = Inter({ subsets: ["latin"], display: "swap" });
export const heebo = Heebo({ subsets: ['latin'], display: "swap" })

全局布局文件(layout.ts)

import type { Metadata } from "next";
import "./globals.css";
import { inter } from './fonts';


export const metadata: Metadata = {
  title: "NextJS Stack Overflow Test.",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={inter.className}>{children}</body>
    </html>
  );
}

页面文件(page.tsx)

import { heebo } from './fonts';

export default function Home() {
  return (
    <>
      <h1 className={`text-center ${heebo.className} white`}>Heebo</h1>
      <h2 className='text-center white'>Roboto</h2>
    </>
  );
}

按上述配置后,page.tsx中的两个测试标题均显示为Roboto字体,而非预期的Heebo和Inter。


问题原因及解决方法

1. 排查Tailwind CSS默认字体覆盖(最可能原因)

如果项目使用Tailwind CSS,它的默认字体栈会优先于Next.js字体组件生成的类名生效。需要在tailwind.config.ts中手动注册自定义字体族:

import type { Config } from 'tailwindcss'
import { inter, heebo } from './app/fonts' // 根据你的文件路径调整

const config: Config = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',
    './app/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    extend: {
      fontFamily: {
        inter: [inter.style.fontFamily, ...inter.style.fontFamily],
        heebo: [heebo.style.fontFamily, ...heebo.style.fontFamily],
      },
    },
  },
  plugins: [],
}
export default config

之后在页面中使用Tailwind的自定义字体类名:

export default function Home() {
  return (
    <>
      <h1 className="text-center font-heebo white">Heebo</h1>
      <h2 className="text-center font-inter white">Inter</h2>
    </>
  );
}

2. 检查全局CSS冲突

如果没有使用Tailwind,打开globals.css查看是否存在全局字体样式,比如:

body {
  font-family: Roboto, sans-serif;
}

这种全局规则会覆盖Next.js字体组件的类名,需要调整优先级(比如给字体类名添加!important),或者修改全局字体栈,将Next.js的字体变量加入:

body {
  font-family: var(--font-inter), sans-serif;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 03:04:52