Next.js自定义Amazon Ember字体开发正常构建后异常求助
问题
在Next.js项目中使用Amazon Ember自定义字体,已在lib目录创建font.ts并按教程配置,开发服务器运行正常,但本地构建后出现以下异常:
- 首次访问
localhost:3000时CSS未加载 - 跳转至
auth页面后CSS加载正常 - 返回首页后CSS正常,但字体未加载,显示fallback的
sans-serif/arial(而非设置的Amazon Ember)
注:未使用默认根布局,采用分组路由,每个路由有独立布局。曾出现过首页字体正常但CSS未加载、auth页面CSS正常但字体未加载的矛盾情况。
相关代码
lib/font.ts
import localFont from "next/font/local"; const Ember = localFont({ src: [ { path: "../app/AmazonEmber_Th.ttf", weight: "100", style: "normal", }, { path: "../app/AmazonEmber_Lt.ttf", weight: "200", style: "normal", }, { path: "../app/AmazonEmber_Rg.ttf", weight: "400", style: "normal", }, { path: "../app/Amazon-Ember-Medium.ttf", weight: "500", style: "normal", }, { path: '../app/AmazonEmber_Bd.ttf', weight: "700", style: "normal", }, { path: '../app/AmazonEmber_He.ttf', weight: "900", style: "normal", } ], variable: "--font-ember", display: "swap", fallback: ["sans-serif", "arial"], }); export { Ember };
tailwind.config.ts
import type { Config } from "tailwindcss" const config = { theme: { fontFamily: { Ember: ['var(--font-ember)', 'sans-serif'] } }, plugins: [require("tailwindcss-animate")], } satisfies Config export default config
根布局代码
<body className={`${Ember.className} font-Ember`}>
解决方案
1. 修正字体文件路径解析问题
lib/font.ts中使用../app/的跨目录相对路径,容易导致构建时资源解析异常。可以选择两种修改方式:
- 将字体文件移至
public/fonts目录,路径改为../../public/fonts/AmazonEmber_Th.ttf(其余字体路径同理) - 将
font.ts移至app/lib目录,路径改为./AmazonEmber_Th.ttf,避免跨目录引用
2. 确保所有分组路由布局都加载字体
因使用分组路由且每个路由有独立布局,需在所有布局文件中引入Ember字体并添加对应className,否则未加载字体的布局无法识别--font-ember变量:
// 示例:auth分组路由的布局文件 import { Ember } from "@/lib/font"; export default function AuthLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en"> <body className={`${Ember.className} font-Ember`}> {children} </body> </html> ); }
3. 检查字体类名大小写一致性
Tailwind的fontFamily键名Ember大小写敏感,确保所有使用字体的地方className都是font-Ember,和配置完全匹配,避免拼写错误。
4. 强制字体预加载(可选)
在根布局的<head>中显式添加字体样式标签,确保字体资源优先加载:
import { Ember } from "@/lib/font"; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en"> <head> {Ember.style} </head> <body className={`${Ember.className} font-Ember`}> {children} </body> </html> ); }
5. 清理缓存后重新构建
执行以下命令清理旧构建缓存,避免残留文件干扰:
rm -rf .next node_modules npm install npm run build npm run start
内容的提问来源于stack exchange,提问作者Abdullah moiz
相关产品推荐
相关产品推荐

