Next.js 13中使用Tailwind时本地字体无法渲染求助
解决Next.js 13 + localFont + Tailwind字体不渲染问题
以下是针对你代码的排查和修复方案:
1. 验证字体文件路径与名称
- 确认
public/fonts/theseasons-reg-webfont.woff2文件存在,文件名完全匹配(注意大小写,比如.woff2不能写成.WOFF2)。 - localFont的
src路径可尝试改为绝对路径写法:src: "/fonts/theseasons-reg-webfont.woff2"(Next.js会自动从public目录读取,避免相对路径出错)。
2. 完善localFont配置项
添加字体的weight和style属性,确保和字体文件的实际属性匹配:
const seasons = localFont({ src: "../public/fonts/theseasons-reg-webfont.woff2", variable: "--font-seasons", weight: "400", // 对应regular字重,根据字体实际情况调整 style: "normal", });
3. 修复Tailwind字体配置
避免直接覆盖默认sans字体(防止影响其他组件),新增自定义字体类:
const { fontFamily } = require("tailwindcss/defaultTheme"); /** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}", "./app/**/*.{js,ts,jsx,tsx}", ], theme: { extend: { colors: { nude: "#E5DDD6", }, fontFamily: { seasons: ["var(--font-seasons)", ...fontFamily.sans], }, }, }, plugins: [], };
然后在_app.tsx中使用自定义字体类:
function MyApp({ Component, pageProps }: AppProps) { return ( <main className={`${seasons.variable} font-seasons`}> <Component {...pageProps} /> </main> ); }
4. 排查浏览器加载情况
- 打开浏览器开发者工具Network面板,刷新页面,查看字体文件是否成功加载(状态码200)。若显示404,说明路径错误。
- 查看Elements面板,检查
main元素是否包含--font-seasons变量,变量值是否为正确的字体face定义。
5. 适配App Router模式(若使用)
如果你用的是Next.js 13 App Router(存在app目录),建议在app/layout.tsx中配置字体:
import localFont from "@next/font/local"; import "./globals.css"; const seasons = localFont({ src: "../public/fonts/theseasons-reg-webfont.woff2", variable: "--font-seasons", weight: "400", }); export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en" className={seasons.variable}> <body className="font-seasons">{children}</body> </html> ); }
内容的提问来源于stack exchange,提问作者Rishi Patel
相关产品推荐
相关产品推荐

