Next.js 14.2.10中使用next/font下载Inter字体失败求助
问题重现
使用Next.js 14.2.10,通过以下代码导入Inter字体:
import { Inter } from 'next/font/google'; const inter = Inter({ subsets: ['latin'], weight: ['100', '200', '300', '400', '500', '600', '700', '800', '900'], style: ['normal'], variable: '--font-inter', fallback: ['sans-serif'], }); const App = ({ Component, pageProps }: AppPropsWithLayout) => { const getLayout = (Component as NextPageWithLayout).getLayout || ((page) => page); return ( <main className={`${inter.className}`}> <Provider store={store}> <ErrorBoundary>{getLayout(<Component {...pageProps} />)}</ErrorBoundary> </Provider> </main> ); };
编译时出现字体下载错误:
Retrying 1/3...
The user aborted a request.Retrying 2/3...
The user aborted a request.Retrying 3/3...
AbortError: The user aborted a request.
at abort (/Users/shreyak.jain/Documents/Work/test/node_modules/next/dist/compiled/node-fetch/index.js:1:65594)
at EventTarget.abortAndFinalize (/Users/shreyak.jain/Documents/Work/test/node_modules/next/dist/compiled/node-fetch/index.js:1:65814)
at [nodejs.internal.kHybridDispatch] (node:internal/event_target:825:20)
at EventTarget.dispatchEvent (node:internal/event_target:760:26)
at abortSignal (node:internal/abort_controller:370:10)
at AbortController.abort (node:internal/abort_controller:392:5)
at Timeout. (/Users/shreyak.jain/Documents/Work/test/node_modules/next/dist/compiled/@next/font/dist/google/fetch-css-from-google-fonts.js:44:47)
at listOnTimeout (node:internal/timers:573:17)
at process.processTimers (node:internal/timers:514:7) {
type: 'aborted'
}
Failed to downloadInterfrom Google Fonts. Using fallback font instead.
解决方案
延长字体请求超时时间
Next.js默认字体下载超时时间较短,在项目根目录的.env.local文件中添加:NEXT_FONT_GOOGLE_TIMEOUT=30000设置为30秒(可根据网络情况调整),给请求足够的完成时间。
减少请求的字体权重数量
一次性请求9个权重可能导致请求过大超时,先尝试只引入常用权重:const inter = Inter({ subsets: ['latin'], weight: ['400', '500', '700'], // 保留常用权重 style: ['normal'], variable: '--font-inter', fallback: ['sans-serif'], });验证成功后再逐步添加其他权重。
手动下载字体本地引入
若网络问题无法解决,可手动导入字体:- 从Google Fonts下载Inter字体的所需权重和样式文件(优先选
.woff2格式) - 在项目
public/fonts目录下存放字体文件 - 使用
next/font/local替代远程导入:
import localFont from 'next/font/local'; const inter = localFont({ src: [ { path: './fonts/Inter-Thin.woff2', weight: '100', style: 'normal', }, { path: './fonts/Inter-Regular.woff2', weight: '400', style: 'normal', }, // 按需添加其他权重配置 ], variable: '--font-inter', fallback: ['sans-serif'], });- 从Google Fonts下载Inter字体的所需权重和样式文件(优先选
检查网络环境
关闭可能拦截请求的代理、VPN或防火墙,切换网络环境(如从内网切换到公网)测试是否能正常访问Google Fonts服务器。清除Next.js缓存
执行以下命令清除缓存后重新编译:rm -rf .next/cache npm run build
内容的提问来源于stack exchange,提问作者Shreyak Jain

