字体
¥Fonts
next/font
模块会自动优化你的字体并删除外部网络请求,以提高隐私和性能。
¥The next/font
module automatically optimizes your fonts and removes external network requests for improved privacy and performance.
它包含适用于任何字体文件的内置自托管功能。这意味着你可以最佳地加载 Web 字体而不会发生布局偏移。
¥It includes built-in self-hosting for any font file. This means you can optimally load web fonts with no layout shift.
要开始使用 next/font
,请从 next/font/local
或 next/font/google
导入它,使用适当的选项将其作为函数调用,然后设置要应用字体的元素的 className
。例如:
¥To start using next/font
, import it from next/font/local
or next/font/google
, call it as a function with the appropriate options, and set the className
of the element you want to apply the font to. For example:
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>
)
}
字体的作用域限定于其所使用的组件。要将字体应用于整个应用,请将其添加到 根布局。
¥Fonts are scoped to the component they're used in. To apply a font to your entire application, add it to the Root Layout.
Google 字体
¥Google fonts
你可以自动自托管任何 Google 字体。字体作为静态资源存储,并由与你的部署相同的域提供,这意味着当用户访问你的网站时,浏览器不会向 Google 发送任何请求。
¥You can automatically self-host any Google Font. Fonts are included stored as static assets and served from the same domain as your deployment, meaning no requests are sent to Google by the browser when the user visits your site.
要开始使用 Google 字体,请从 next/font/google
导入你选择的字体:
¥To start using a Google Font, import your chosen font from 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="en" className={geist.className}>
<body>{children}</body>
</html>
)
}
我们建议使用 可变字体 以获得最佳性能和灵活性。但如果不能使用可变字体,则需要指定权重:
¥We recommend using variable fonts for the best performance and flexibility. But if you can't use a variable font, you will need to specify a weight:
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>
)
}
本地字体
¥Local fonts
要使用本地字体,请从 next/font/local
导入字体并指定本地字体文件的 src
。字体可以存储在 public
文件夹中。例如:
¥To use a local font, import your font from next/font/local
and specify the src
of your local font file. Fonts can be stored in the public
folder. For example:
import localFont from 'next/font/local'
const myFont = localFont({
src: './my-font.woff2',
})
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={myFont.className}>
<body>{children}</body>
</html>
)
}
如果你想对单个字体系列使用多个文件,src
可以是一个数组:
¥If you want to use multiple files for a single font family, src
can be an array: