Skip to main content

字体优化

next/font 将自动优化你的字体(包括自定义字体)并删除外部网络请求,以提高隐私性和性能。

¥next/font will automatically optimize your fonts (including custom fonts) and remove external network requests for improved privacy and performance.

🎥 监视:了解有关使用 next/fontYouTube(6 分钟) 的更多信息。

¥🎥 Watch: Learn more about using next/fontYouTube (6 minutes).

next/font 包括任何字体文件的内置自动自托管。这意味着,由于使用了底层 CSS size-adjust 属性,你可以以零布局偏移的方式以最佳方式加载 Web 字体。

¥next/font includes built-in automatic self-hosting for any font file. This means you can optimally load web fonts with zero layout shift, thanks to the underlying CSS size-adjust property used.

这个新的字体系统还允许你方便地使用所有 Google 字体,同时考虑到性能和隐私。CSS 和字体文件在构建时下载,并与其余静态资源一起自托管。浏览器不会向 Google 发送任何请求。

¥This new font system also allows you to conveniently use all Google Fonts with performance and privacy in mind. CSS and font files are downloaded at build time and self-hosted with the rest of your static assets. No requests are sent to Google by the browser.

谷歌字体

¥Google Fonts

自动自行托管任何 Google 字体。字体包含在部署中,并由与你的部署相同的域提供服务。浏览器不会向 Google 发送任何请求。

¥Automatically self-host any Google Font. Fonts are included in the deployment and served from the same domain as your deployment. No requests are sent to Google by the browser.

首先从 next/font/google 导入你想要使用的字体作为函数。我们建议使用 可变字体 以获得最佳性能和灵活性。

¥Get started by importing the font you would like to use from next/font/google as a function. We recommend using variable fonts for the best performance and flexibility.

import { Inter } from 'next/font/google'

// If loading a variable font, you don't need to specify the 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>
)
}
import { Inter } from 'next/font/google'

// If loading a variable font, you don't need to specify the 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>
)
}

如果你不能使用可变字体,则需要指定粗细:

¥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'],
display: 'swap',
})

export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={roboto.className}>
<body>{children}</body>
</html>
)
}
import { Roboto } from 'next/font/google'

const roboto = Roboto({
weight: '400',
subsets: ['latin'],
display: 'swap',
})

export default function RootLayout({ children }) {
return (
<html lang="en" className={roboto.className}>
<body>{children}</body>
</html>
)
}

你可以使用数组指定多个权重和/或样式:

¥You can specify multiple weights and/or styles by using an array:

const roboto = Roboto({
weight: ['400', '700'],
style: ['normal', 'italic'],
subsets: ['latin'],
display: 'swap',
})

很高兴知道:对于包含多个单词的字体名称使用下划线 (_)。例如。Roboto Mono 应作为 Roboto_Mono 导入。

¥Good to know: Use an underscore (_) for font names with multiple words. E.g. Roboto Mono should be imported as Roboto_Mono.

指定子集

¥Specifying a subset

Google 字体自动为 subset。这会减小字体文件的大小并提高性能。你需要定义要预加载的子集。当 preloadtrue 时未能指定任何子集将导致警告。

¥Google Fonts are automatically subset. This reduces the size of the font file and improves performance. You'll need to define which of these subsets you want to preload. Failing to specify any subsets while preload is true will result in a warning.

这可以通过将其添加到函数调用中来完成:

¥This can be done by adding it to the function call:

const inter = Inter({ subsets: ['latin'] })
const inter = Inter({ subsets: ['latin'] })

查看 字体 API 参考 了解更多信息。

¥View the Font API Reference for more information.

使用多种字体

¥Using Multiple Fonts

你可以在应用中导入和使用多种字体。你可以采取两种方法。

¥You can import and use multiple fonts in your application. There are two approaches you can take.

第一种方法是创建一个实用程序函数,用于导出字体、导入字体并在需要时应用其 className。这确保字体仅在渲染时才预加载:

¥The first approach is to create a utility function that exports a font, imports it, and applies its className where needed. This ensures the font is preloaded only when it's rendered:

import { Inter, Roboto_Mono } from 'next/font/google'

export const inter = Inter({
subsets: ['latin'],
display: 'swap',
})

export const roboto_mono = Roboto_Mono({
subsets: ['latin'],
display: 'swap',
})
import { Inter, Roboto_Mono } from 'next/font/google'

export const inter = Inter({
subsets: ['latin'],
display: 'swap',
})

export const roboto_mono = Roboto_Mono({
subsets: ['latin'],
display: 'swap',
})
import { inter } from './fonts'

export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className={inter.className}>
<body>
<div>{children}</div>
</body>
</html>
)
}
import { inter } from './fonts'

export default function Layout({ children }) {
return (
<html lang="en" className={inter.className}>
<body>
<div>{children}</div>
</body>
</html>
)
}
import { roboto_mono } from './fonts'

export default function Page() {
return (
<>
<h1 className={roboto_mono.className}>My page</h1>
</>
)
}
import { roboto_mono } from './fonts'

export default function Page() {
return (
<>
<h1 className={roboto_mono.className}>My page</h1>
</>
)
}

上例中,Inter 会全局应用,Roboto Mono 可以根据需要导入应用。

¥In the example above, Inter will be applied globally, and Roboto Mono can be imported and applied as needed.

或者,你可以创建 CSS 变量 并将其与你首选的 CSS 解决方案一起使用:

¥Alternatively, you can create a CSS variable and use it with your preferred CSS solution:

import { Inter, Roboto_Mono } from 'next/font/google'
import styles from './global.css'

const inter = Inter({
subsets: ['latin'],
variable: '--font-inter',
display: 'swap',
})

const roboto_mono = Roboto_Mono({
subsets: ['latin'],
variable: '--font-roboto-mono',
display: 'swap',
})

export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}>
<body>
<h1>My App</h1>
<div>{children}</div>
</body>
</html>
)
}
import { Inter, Roboto_Mono } from 'next/font/google'

const inter = Inter({
subsets: ['latin'],
variable: '--font-inter',
display: 'swap',
})

const roboto_mono = Roboto_Mono({
subsets: ['latin'],
variable: '--font-roboto-mono',
display: 'swap',
})

export default function RootLayout({ children }) {
return (
<html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}>
<body>
<h1>My App</h1>
<div>{children}</div>
</body>
</html>
)
}
html {
font-family: var(--font-inter);
}

h1 {
font-family: var(--font-roboto-mono);
}

在上面的示例中,Inter 将全局应用,任何 <h1> 标签都将使用 Roboto Mono 进行样式设置。

¥In the example above, Inter will be applied globally, and any <h1> tags will be styled with Roboto Mono.

推荐:谨慎使用多种字体,因为每种新字体都是客户端必须下载的额外资源。

¥Recommendation: Use multiple fonts conservatively since each new font is an additional resource the client has to download.

本地字体

¥Local Fonts

导入 next/font/local 并指定本地字体文件的 src。我们建议使用 可变字体 以获得最佳性能和灵活性。

¥Import next/font/local and specify the src of your local font file. We recommend using variable fonts for the best performance and flexibility.

import localFont from 'next/font/local'

// Font files can be colocated inside of `app`
const myFont = localFont({
src: './my-font.woff2',
display: 'swap',
})

export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={myFont.className}>
<body>{children}</body>
</html>
)
}
import localFont from 'next/font/local'

// Font files can be colocated inside of `app`
const myFont = localFont({
src: './my-font.woff2',
display: 'swap',
})

export default function RootLayout({ children }) {
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:

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',
},
],
})

查看 字体 API 参考 了解更多信息。

¥View the Font API Reference for more information.

使用 Tailwind CSS

¥With Tailwind CSS

next/font 可通过 CSS 变量Tailwind CSS 一起使用。

¥next/font can be used with Tailwind CSS through a CSS variable.

在下面的示例中,我们使用 next/font/google 中的字体 Inter(你可以使用 Google 或本地字体中的任何字体)。使用 variable 选项加载字体以定义 CSS 变量名称并将其分配给 inter。然后,使用 inter.variable 将 CSS 变量添加到 HTML 文档中。

¥In the example below, we use the font Inter from next/font/google (you can use any font from Google or Local Fonts). Load your font with the variable option to define your CSS variable name and assign it to inter. Then, use inter.variable to add the CSS variable to your HTML document.

import { Inter, Roboto_Mono } from 'next/font/google'

const inter = Inter({
subsets: ['latin'],
display: 'swap',
variable: '--font-inter',
})

const roboto_mono = Roboto_Mono({
subsets: ['latin'],
display: 'swap',
variable: '--font-roboto-mono',
})

export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}>
<body>{children}</body>
</html>
)
}
import { Inter, Roboto_Mono } from 'next/font/google'

const inter = Inter({
subsets: ['latin'],
display: 'swap',
variable: '--font-inter',
})

const roboto_mono = Roboto_Mono({
subsets: ['latin'],
display: 'swap',
variable: '--font-roboto-mono',
})

export default function RootLayout({ children }) {
return (
<html lang="en" className={`${inter.variable} ${roboto_mono.variable}`}>
<body>{children}</body>
</html>
)
}

最后,将 CSS 变量添加到 Tailwind CSS 配置

¥Finally, add the CSS variable to your Tailwind CSS config:

/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
'./app/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {
fontFamily: {
sans: ['var(--font-inter)'],
mono: ['var(--font-roboto-mono)'],
},
},
},
plugins: [],
}

你现在可以使用 font-sansfont-mono 实用程序类将字体应用到你的元素。

¥You can now use the font-sans and font-mono utility classes to apply the font to your elements.

预加载

¥Preloading

当在站点的页面上调用字体函数时,它不是全局可用的,也不是在所有路由上预加载的。相反,字体仅根据使用的文件类型预加载到相关路径上:

¥When a font function is called on a page of your site, it is not globally available and preloaded on all routes. Rather, the font is only preloaded on the related routes based on the type of file where it is used:

  • 如果它是 独特的页面,它将预加载到该页面的唯一路由上。

    ¥If it's a unique page, it is preloaded on the unique route for that page.

  • 如果它是 layout,它将预加载到布局包含的所有路由上。

    ¥If it's a layout, it is preloaded on all the routes wrapped by the layout.

  • 如果是 根布局,则会在所有路由上预加载。

    ¥If it's the root layout, it is preloaded on all routes.

重用字体

¥Reusing fonts

每次调用 localFont 或 Google 字体函数时,该字体都会作为一个实例托管在你的应用中。因此,如果你在多个文件中加载相同的字体函数,则会托管相同字体的多个实例。在这种情况下,建议执行以下操作:

¥Every time you call the localFont or Google font function, that font is hosted as one instance in your application. Therefore, if you load the same font function in multiple files, multiple instances of the same font are hosted. In this situation, it is recommended to do the following:

  • 在一个共享文件中调用字体加载函数

    ¥Call the font loader function in one shared file

  • 将其导出为常量

    ¥Export it as a constant

  • 在你想要使用此字体的每个文件中导入常量

    ¥Import the constant in each file where you would like to use this font