Font Module
next/font 会自动优化你的字体(包括自定义字体),并移除外部网络请求,从而提升隐私和性能。
它为任意字体文件提供内置自动自托管。这意味着你可以无 布局偏移地(layout shift)最佳加载 Web 字体。
你还可以便捷地使用所有 Google Fonts。CSS 和字体文件会在构建时下载,并与其他静态资源一起自托管。浏览器不会向 Google 发送任何请求。
- TypeScript
- JavaScript
app/layout.tsx
import { Inter } from 'next/font/google'
// 加载可变字体时,无需指定 font weight
const inter = Inter({
subsets: ['latin'],
display: 'swap',
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={inter.className}>
<body>{children}</body>
</html>
)
}
app/layout.js
import { Inter } from 'next/font/google'
// 加载可变字体时,无需指定 font weight
const inter = Inter({
subsets: ['latin'],
display: 'swap',
})
export default function RootLayout({ children }) {
return (
<html lang="en" className={inter.className}>
<body>{children}</body>
</html>
)
}
🎥 视频讲解: 了解更多关于
next/font的用法 → YouTube(6 分钟)。
参考
| 键 | font/google | font/local | 类型 | 是否必填 |
|---|---|---|---|---|
src | ❌ | ✅ | 字符串或对象数组 | 是 |
weight | ✅ | ✅ | 字符串或数组 | 必填/可选 |
style | ✅ | ✅ | 字符串或数组 | - |
subsets | ✅ | ❌ | 字符串数组 | - |
axes | ✅ | ❌ | 字符串数组 | - |
display | ✅ | ✅ | 字符串 | - |
preload | ✅ | ✅ | 布尔值 | - |
fallback | ✅ | ✅ | 字符串数组 | - |
adjustFontFallback | ✅ | ✅ | 布尔值或字符串 | - |
variable | ✅ | ✅ | 字符串 | - |
declarations | ❌ | ✅ | 对象数组 | - |