font 字体
2026年9月6日
next/font 在构建期把字体文件和样式收进自己的静态资源,运行时不再请求 fonts.google.com。配套一份接近的 fallback,减少字体换完之后的布局跳动(CLS)。
Google 字体
import { Inter } from "next/font/google";
const inter = Inter({
subsets: ["latin"],
display: "swap",
});
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="zh-CN">
<body className={inter.className}>{children}</body>
</html>
);
}
tsx
className 挂到 body 或某一层容器即可。可变字体可以一次要多个字重:
import { Roboto } from "next/font/google";
const roboto = Roboto({
weight: ["400", "700"],
style: ["normal", "italic"],
subsets: ["latin"],
display: "swap",
});
tsx
不是每种字体都支持可变轴,以 Google Fonts 和类型提示为准。中文常用 Noto Sans SC、思源,注意 subset 和包体大小。
display 策略
| 值 | 行为 |
|---|---|
auto | 浏览器默认,多半接近 block |
block | 先空白约 3s,再 fallback,最后自定义字体 |
swap | 先 fallback,字体到了再换(常用) |
fallback | 极短空白 → fallback,约 3s 内到了再换 |
optional | 很短窗口内到了才用自定义字体,否则放弃 |
正文阅读页多用 swap:先看到字,再微调字形。
本地字体
import localFont from "next/font/local";
const face = localFont({
src: "./fonts/brand.woff2",
display: "swap",
});
tsx
多文件按字重列数组:
const face = localFont({
src: [
{ path: "./fonts/brand-regular.woff2", weight: "400" },
{ path: "./fonts/brand-bold.woff2", weight: "700" },
],
});
tsx
授权要看清:免费可商用和「个人用」不是一回事。
常用选项
| 选项 | 本地 | 说明 | |
|---|---|---|---|
src | ✓ | 文件路径 | |
weight / style | ✓ | ✓ | 字重、斜体 |
subsets | ✓ | 字符子集 | |
display | ✓ | ✓ | 见上表 |
preload | ✓ | ✓ | 是否预加载 |
fallback | ✓ | ✓ | 备用字体栈 |
adjustFontFallback | ✓ | ✓ | 调整 fallback 度量,减 CLS |
variable | ✓ | ✓ | 生成 CSS 变量名,方便和 Tailwind 搭配 |
const inter = Inter({
subsets: ["latin"],
variable: "--font-inter",
});
// <body className={inter.variable}>
// CSS: font-family: var(--font-inter), sans-serif;
tsx
下一篇:next/script,第三方脚本何时加载。