字体优化
next/font 能自动优化字体加载:
- 所有字体 自托管 成静态资源,浏览器不再向 Google 发请求。
- 自动消除布局抖动(CLS)。
- 字体只在用到的组件范围内生效,天然范围化。
Google Fonts
从 next/font/google 里直接导入字体并作为函数调用即可:
import { Geist } from 'next/font/google';
const geist = Geist({ subsets: ['latin'] });
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="zh-CN" className={geist.className}>
<body>{children}</body>
</html>
);
}
- 推荐使用 variable font,灵活且体积合理。
- 普通字体则需要明确指定
weight:
import { Roboto } from 'next/font/google';
const roboto = Roboto({ weight: '400', subsets: ['latin'] });
本地字体
把 .woff2 放到项目里(比如 app/fonts/ 或 public/fonts/),用 next/font/local:
import localFont from 'next/font/local';
const myFont = localFont({ src: './my-font.woff2' });
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="zh-CN" className={myFont.className}>
<body>{children}</body>
</html>
);
}
一组多权重/斜体?用数组:
const roboto = localFont({
src: [
{ path: './Roboto-Regular.woff2', weight: '400', style: 'normal' },
{ path: './Roboto-Italic.woff2', weight: '400', style: 'italic' },
{ path: './Roboto-Bold.woff2', weight: '700', style: 'normal' },
{ path: './Roboto-BoldItalic.woff2', weight: '700', style: 'italic' },
],
});
作用域
字体是「用在哪里就作用于哪里」。把它写在根布局可全站生效,写在 app/blog/layout.tsx 就只影响博客区。这样你可以在不同路由用不同字体,互不干扰。
与 Tailwind 搭配
给字体起一个 CSS 变量,在 Tailwind 配置里映射成字体家族:
import { Geist } from 'next/font/google';
const geist = Geist({
subsets: ['latin'],
variable: '--font-geist',
});
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html className={geist.variable}>
<body>{children}</body>
</html>
);
}
/* app/globals.css */
@theme {
--font-sans: var(--font-geist);
}
这样 font-sans 工具类就会用上 Geist。