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

NextJS中Google Fonts无法正常显示的问题排查求助

Next.js + MUI 配置Google Fonts失效的解决方案

问题根源

你的配置存在两个核心错误:

  • 误用了roboto.className拼接字体族:Next.js Font返回的className是用于全局挂载字体样式的类名,并非字体名称本身;
  • 未在应用根组件中添加字体的className:导致字体文件根本没有被加载到页面中。

修复步骤

1. 修正字体族的定义方式

在commonStyles.ts中,改用字体对象的style.fontFamily属性(该属性返回字体的正式名称)来定义字体族:

// commonStyles.ts
import { roboto, notoSerifHebrew } from "../assets/typography";
// 用style.fontFamily获取字体名称,替代className
export const hebrewFamily = `${notoSerifHebrew.style.fontFamily}, "Times New Roman", serif`;
export const englishFamily = `${roboto.style.fontFamily}, Arial, sans-serif`;

const commonStyles = {
  typography: {
    fontFamily: englishFamily,
    hebrewFamily: hebrewFamily,
    englishFamily: englishFamily,
  },
  components: {
    MuiCssBaseline: {
      styleOverrides: {
        a: {
          textDecoration: "none",
          color: "inherit",
        },
      },
    },
  },
};

export default commonStyles;

2. 在根组件中挂载字体类名

Next.js的字体优化需要将生成的className添加到全局容器,确保字体的@font-face样式被注入页面:

  • App Router(Next.js 13+):在app/layout.tsx中添加
import { roboto, notoSerifHebrew } from "@/assets/typography";
import { ThemeProvider } from "@mui/material/styles";
import CssBaseline from "@mui/material/CssBaseline";
import lightTheme from "@/configurations/lightTheme";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={`${roboto.className} ${notoSerifHebrew.className}`}>
      <body>
        <ThemeProvider theme={lightTheme}>
          <CssBaseline />
          {children}
        </ThemeProvider>
      </body>
    </html>
  );
}
  • Pages Router:在pages/_app.tsx中添加
import { roboto, notoSerifHebrew } from "../assets/typography";
import { ThemeProvider } from "@mui/material/styles";
import CssBaseline from "@mui/material/CssBaseline";
import lightTheme from "../configurations/lightTheme";

function MyApp({ Component, pageProps }) {
  return (
    <div className={`${roboto.className} ${notoSerifHebrew.className}`}>
      <ThemeProvider theme={lightTheme}>
        <CssBaseline />
        <Component {...pageProps} />
      </ThemeProvider>
    </div>
  );
}

export default MyApp;

3. 验证直接指定字体的效果

完成上述配置后,sx={{ fontFamily: "Roboto" }}这类直接指定字体名称的写法会生效,因为字体文件已被正确加载,且Next.js Font会自动注册字体名称到全局样式中。

额外说明

  • className的作用是注入字体的加载样式,必须全局挂载才能触发字体文件下载;
  • style.fontFamily返回的是字体的标准名称(如"Roboto"),适合直接用于CSS的font-family属性;
  • 确保subsets配置覆盖你的语言场景,比如希伯来文需要hebrew子集。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 00:43:21