开发模式下Next.js字体加载异常问题求助
Next.js next/font/google 开发模式下字体加载不稳定问题
问题描述
使用next/font/google导入谷歌字体搭建字体选择器,搭配Tailwind CSS使用,但开发模式下字体加载状态不稳定——时而全部正常加载、时而仅加载部分、时而完全失败。已尝试清除缓存、重启服务器、删除.next文件夹等操作,问题仍未得到可靠解决。
代码示例
// ..app/fonts.ts export const merriweather = Merriweather({ subsets: ['latin'], weight: ['400', '700', '900'], variable: '--merriweather', display: 'swap', }) export const roboto = Roboto({ subsets: ['latin'], weight: ['400', '700', '900'], variable: '--roboto', display: 'swap', }) export const fonts = [merriweather, roboto]
// ..app/layout.tsx export default function RootLayout({children}: Readonly<{ children: React.ReactNode}>) { const fontVariables = fonts.map((font) => font.variable).join(' ') return ( <html lang='en'> <body className={{fontVariables}}> {children} <Toaster /> </body> </html> ) }
// tailwind.config.ts extend: { fontFamily: { merriweather: ['var(--merriweather)'], roboto: ['var(--roboto)'] }
解决方法
1. 修复layout.tsx中className的错误写法
你在body标签里错误使用了对象语法className={{fontVariables}},这会导致CSS变量无法正确注入DOM,应该直接传递字符串变量:
// ..app/layout.tsx export default function RootLayout({children}: Readonly<{ children: React.ReactNode}>) { const fontVariables = fonts.map((font) => font.variable).join(' ') return ( <html lang='en'> {/* 修正为直接传递字符串变量 */} <body className={fontVariables}> {children} <Toaster /> </body> </html> ) }
2. 显式控制字体预加载策略
开发模式下Next.js的字体预加载逻辑可能存在偶发异常,显式开启preload选项确保字体资源优先加载:
// ..app/fonts.ts export const merriweather = Merriweather({ subsets: ['latin'], weight: ['400', '700', '900'], variable: '--merriweather', display: 'swap', preload: true, }) export const roboto = Roboto({ subsets: ['latin'], weight: ['400', '700', '900'], variable: '--roboto', display: 'swap', preload: true, })
3. 将字体变量挂载到html标签
部分场景下body标签的样式加载顺序可能影响变量生效,尝试将变量移到html标签:
// ..app/layout.tsx export default function RootLayout({children}: Readonly<{ children: React.ReactNode}>) { const fontVariables = fonts.map((font) => font.variable).join(' ') return ( <html lang='en' className={fontVariables}> <body> {children} <Toaster /> </body> </html> ) }
4. 禁用热重载测试验证
热重载可能导致资源请求异常,临时禁用热重载确认是否为该问题:
next dev --no-hmr
5. 升级Next.js到最新稳定版
部分旧版本的next/font存在开发模式加载bug,升级到最新版可修复已知问题:
npm install next@latest
内容的提问来源于stack exchange,提问作者haskinator
相关产品推荐
相关产品推荐

