字体优化
原文地址:https://nextjs.org/docs/app/getting-started/fonts
next/font 模块会自动优化您的字体并删除外部网络请求,以提高隐私性和性能。
它包括任何字体文件的内置自托管。这意味着您可以以最佳方式加载网络字体,而无需更改布局。
要开始使用 next/font ,请从 next/font/local 或 next/font/google 导入它,将其作为具有适当选项的函数调用,然后设置要应用字体的元素的 className 。例如:
| app/layout.tsx |
|---|
| import { Geist } from 'next/font/google'
const geist = Geist({
subsets: ['latin'],
})
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className={geist.className}>
<body>{children}</body>
</html>
)
}
|
字体的范围仅限于它们所使用的组件。要将字体应用到整个应用程序,请将其添加到根布局。
1. Google 字体
您可以自动自行托管任何 Google 字体。字体作为静态资产存储,并从与您的部署相同的域提供服务,这意味着当用户访问您的网站时,浏览器不会向 Google 发送任何请求。
要开始使用 Google 字体,请从 next/font/google 导入您选择的字体:
| app/layout.tsx |
|---|
| import { Geist } from 'next/font/google'
const geist = Geist({
subsets: ['latin'],
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={geist.className}>
<body>{children}</body>
</html>
)
}
|
我们建议使用可变字体以获得最佳性能和灵活性。但如果您不能使用可变字体,则需要指定粗细:
| app/layout.tsx |
|---|
| import { Roboto } from 'next/font/google'
const roboto = Roboto({
weight: '400',
subsets: ['latin'],
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={roboto.className}>
<body>{children}</body>
</html>
)
}
|
2. 本地字体