字体模块
使用内置的 next/font 加载器优化 Web 字体的加载。
next/font 会自动优化你的字体(包括自定义字体),并移除外部网络请求,从而提升隐私保护和性能。
它为任何字体文件提供了内置的自动自托管。这意味着你可以以最佳方式加载 Web 字体,且不会出现布局偏移。
你还可以方便地使用所有 Google Fonts。CSS 和字体文件会在构建时下载,并与其他静态资源一起自托管。浏览器不会向 Google 发送任何请求。
TypeScript
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>
)
}
JavaScript
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>
)
}
🎥 观看:
进一步了解如何使用
next/font→ YouTube(6 分钟)。
参考
| 键 | font/google |
font/local |
类型 | 是否必需 |
|---|---|---|---|---|
src |
✗ | ✓ | 字符串或对象数组 | 是 |
weight |
✓ | ✓ | 字符串或数组 | 必需/可选 |
style |
✓ | ✓ | 字符串或数组 | - |
subsets |
✓ | ✗ | 字符串数组 | - |
axes |
✓ | ✗ | 字符串数组 | - |
display |
✓ | ✓ | 字符串 | - |
preload |
✓ | ✓ | 布尔值 | - |
fallback |
✓ | ✓ | 字符串数组 | - |
adjustFontFallback |
✓ | ✓ | 布尔值或字符串 | - |
variable |
✓ | ✓ | 字符串 | - |
declarations |
✗ | ✓ | 对象数组 | - |
src
字体文件的路径,可以是字符串或对象数组(类型为 Array<{path: string, weight?: string, style?: string}>),相对于调用字体加载器函数的目录。
用于 next/font/local
- 必需
示例:
src:'./fonts/my-font.woff2',其中my-font.woff2位于app目录下名为fonts的目录中src:[{path: './inter/Inter-Thin.ttf', weight: '100',},{path: './inter/Inter-Regular.ttf',weight: '400',},{path: './inter/Inter-Bold-Italic.ttf', weight: '700',style: 'italic',},]- 如果在
app/page.tsx中使用src:'../styles/fonts/my-font.ttf'调用字体加载器函数,则my-font.ttf位于项目根目录的styles/fonts中
weight
字体 weight,有以下可能取值:
- 一个字符串,包含该特定字体可用的字重值,或者如果是可变字体,则为字重范围
- 如果字体不是可变 Google 字体,则为字重值数组。仅适用于
next/font/google。
用于 next/font/google 和 next/font/local
- 如果使用的字体不是可变字体,则为必需
示例:
weight: '400':单个字重值的字符串 - 对于字体Inter,可能的值为'100'、'200'、'300'、'400'、'500'、'600'、'700'、'800'、'900'或'variable',其中'variable'为默认值weight: '100 900':可变字体的一个字符串,表示100到900之间的范围weight: ['100','400','900']:非可变字体的 3 个可能值组成的数组
style
字体 style,有以下可能取值:
- 一个字符串值,默认值为
'normal' - 如果字体不是可变 Google 字体,则为样式值数组。仅适用于
next/font/google。
用于 next/font/google 和 next/font/local
- 可选
示例:
style: 'italic':一个字符串 - 对于next/font/google,可以是normal或italicstyle: 'oblique':字符串 - 对于next/font/local可以取任意值,但预期来自标准字体样式style: ['italic','normal']:用于next/font/google的包含 2 个值的数组 - 这些值来自normal和italic
subsets
字体 subsets 由一个字符串值数组定义,其中的字符串值为你希望预加载的各个子集名称。当 preload 选项为 true(这是默认值)时,通过 subsets 指定的字体会向 head 中注入一个 link preload 标签。
用于 next/font/google
- 可选
示例:
subsets: ['latin']:包含子集latin的数组
你可以在所用字体的 Google Fonts 页面上找到所有子集的列表。
axes
某些可变字体具有可以包含的额外 axes。默认情况下,仅包含字重以减小文件大小。axes 的可能值取决于具体字体。
用于 next/font/google
- 可选
示例:
axes: ['slnt']:一个数组,其值为slnt,用于Inter可变字体;该字体具有slnt作为额外的axes,如此处所示。你可以使用 Google 可变字体页面 上的筛选器并查找除wght以外的轴,来找到你的字体可用的axes值。
display
字体 display,其可能的字符串值为 'auto'、'block'、'swap'、'fallback' 或 'optional',默认值为 'swap'。
用于 next/font/google 和 next/font/local
- 可选
示例:
display: 'optional':分配给optional值的字符串
preload
一个布尔值,用于指定字体是否应预加载。默认值为 true。
一次调用所加载的每个字体文件都共享此设置,因为它们会组成一组 @font-face 规则,并共用同一个 font-family。
用于 next/font/google 和 next/font/local
- 可选
示例:
preload: false
fallback
字体无法加载时使用的回退字体。回退字体的字符串数组,无默认值。
- 可选
用于 next/font/google 和 next/font/local
示例:
fallback: ['system-ui', 'arial']:一个数组,将后备字体设置为system-ui或arial
adjustFontFallback
- 对于
next/font/google:一个布尔值,用于设置是否应使用自动后备字体来减少 累积布局偏移。默认值为true。 - 对于
next/font/local:一个字符串或布尔类型的false值,用于设置是否应使用自动后备字体来减少 累积布局偏移。可选值为'Arial'、'Times New Roman'或false。默认值为'Arial'。
用于 next/font/google 和 next/font/local
- 可选
示例:
adjustFontFallback: false:用于next/font/googleadjustFontFallback: 'Times New Roman':用于next/font/local
variable
一个字符串值,用于定义在以 CSS 变量方式应用样式时要使用的 CSS 变量名。
用于 next/font/google 和 next/font/local
- 可选
示例:
variable: '--my-font':声明了 CSS 变量--my-font
declarations
一个字体面 描述符键值对数组,用于进一步定义生成的 @font-face。
设置 font-family 会替换 Next.js 生成的名称。请让该值与导出的常量保持一致,以便 className 和 CSS 变量引用同一个字体族。
import localFont from 'next/font/local'
export const myFont = localFont({
src: './my-font.woff2',
declarations: [{ prop: 'font-family', value: 'myFont' }],
})
用于 next/font/local
- 可选
示例:
declarations: [{ prop: 'ascent-override', value: '90%' }]
示例
Google Fonts
要使用 Google 字体,请从 next/font/google 中将其作为函数导入。我们建议使用可变字体,以获得最佳性能和灵活性。
TypeScript
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>
)
}
JavaScript
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>
)
}
如果你无法使用可变字体,你将需要指定字重:
TypeScript
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>
)
}
JavaScript
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>
)
}
你可以使用数组来指定多个字重和/或样式:
const roboto = Roboto({
weight: ['400', '700'],
style: ['normal', 'italic'],
subsets: ['latin'],
display: 'swap',
})
须知:
对于包含多个单词的字体名称,请使用下划线(_)。例如,
Roboto Mono应导入为Roboto_Mono。
指定子集
Google Fonts 会自动进行子集化。这会减小字体文件的大小并提升性能。你需要定义想要预加载哪些子集。在 preload 为 true 时未指定任何子集,将会产生警告。
可以通过将其添加到函数调用中来实现:
TypeScript
const inter = Inter({ subsets: ['latin'] })
JavaScript
const inter = Inter({ subsets: ['latin'] })
查看 Font API 参考 以了解更多信息。
使用多个字体
你可以在应用程序中导入并使用多个字体。有两种方法可供选择。
第一种方法是创建一个导出字体的工具函数,在需要的地方导入它并应用其 className。这确保字体只在其被渲染时才预加载:
TypeScript
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 { roboto_mono } from './fonts'
export default function Page() {
return (
<>
<h1 className={roboto_mono.className}>My page</h1>
</>
)
}
JavaScript
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 }) {
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>
</>
)
}
在上面的示例中,Inter 将全局应用,而 Roboto Mono 可以按需导入并应用。
或者,你可以创建一个 CSS 变量,并将其与你偏好的 CSS 方案一起使用:
TypeScript
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>
)
}
JavaScript
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 进行样式设置。
建议:
谨慎使用多种字体,因为每新增一种字体都是客户端必须额外下载的资源。
本地字体
导入 next/font/local 并指定本地字体文件的 src。我们推荐使用可变字体,以获得最佳的性能和灵活性。
TypeScript
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>
)
}
JavaScript
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 可以是一个数组:
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',
},
],
})
更多信息请参阅 Font API 参考。
配合 Tailwind CSS 使用
next/font 通过 CSS 变量与 Tailwind CSS 无缝集成。
在下面的示例中,我们使用来自 next/font/google 的 Inter 和 Roboto_Mono 字体(你可以使用任何 Google 字体或本地字体)。使用 variable 选项定义一个 CSS 变量名,例如分别为这些字体指定 inter 和 roboto_mono。然后,应用 inter.variable 和 roboto_mono.variable 将这些 CSS 变量包含到你的 HTML 文档中。
须知:
你可以根据个人偏好、样式需求或项目要求,将这些变量添加到
<html>或<body>标签中。
TypeScript
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} antialiased`}
>
<body>{children}</body>
</html>
)
}
JavaScript
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} antialiased`}
>
<body>{children}</body>
</html>
)
}
最后,将 CSS 变量添加到你的 Tailwind CSS 配置中:
@import 'tailwindcss';
@theme inline {
--font-sans: var(--font-inter);
--font-mono: var(--font-roboto-mono);
}
Tailwind CSS v3
/** @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-sans 和 font-mono 工具类将字体应用到你的元素上。
<p class="font-sans ...">The quick brown fox ...</p>
<p class="font-mono ...">The quick brown fox ...</p>
应用样式
你可以通过三种方式应用字体样式:
className
返回已加载字体的只读 CSS className,可传递给 HTML 元素。
<p className={inter.className}>Hello, Next.js!</p>
style
返回已加载字体的只读 CSS style 对象,可传递给 HTML 元素,其中包含 style.fontFamily,用于访问字体家族名称和后备字体。
<p style={inter.style}>Hello World</p>
CSS 变量
如果你想在外部样式表中设置样式并在那里指定其他选项,请使用 CSS 变量方法。
除了导入字体之外,还要导入定义 CSS 变量的 CSS 文件,并按如下方式设置字体加载器对象的 variable 选项:
TypeScript
import { Inter } from 'next/font/google'
import styles from '../styles/component.module.css'
const inter = Inter({
variable: '--font-inter',
})
JavaScript
import { Inter } from 'next/font/google'
import styles from '../styles/component.module.css'
const inter = Inter({
variable: '--font-inter',
})
要使用该字体,请将你想设置样式的文本的父容器的 className 设置为字体加载器的 variable 值,并将该文本的 className 设置为外部 CSS 文件中的 styles 属性。
TypeScript
<main className={inter.variable}>
<p className={styles.text}>Hello World</p>
</main>
JavaScript
<main className={inter.variable}>
<p className={styles.text}>Hello World</p>
</main>
在 component.module.css CSS 文件中按如下方式定义 text 选择器类:
.text {
font-family: var(--font-inter);
font-weight: 200;
font-style: italic;
}
在上面的示例中,文本 Hello World 使用 Inter 字体以及使用 font-weight: 200 和 font-style: italic 生成的字体回退进行样式设置。
使用字体定义文件
每次调用 localFont 或 Google 字体函数时,该字体都会作为单个实例托管在你的应用中。因此,如果你需要在多个位置使用同一字体,应在一个位置加载它,并在需要的地方导入相关的字体对象。这可以通过字体定义文件来实现。
例如,在你的应用目录根部的 styles 文件夹中创建一个 fonts.ts 文件。
然后,按如下方式指定你的字体定义:
TypeScript
import { Inter, Lora, Source_Sans_3 } from 'next/font/google'
import localFont from 'next/font/local'
// define your variable fonts
const inter = Inter()
const lora = Lora()
// define 2 weights of a non-variable font
const sourceCodePro400 = Source_Sans_3({ weight: '400' })
const sourceCodePro700 = Source_Sans_3({ weight: '700' })
// define a custom local font where GreatVibes-Regular.ttf is stored in the styles folder
const greatVibes = localFont({ src: './GreatVibes-Regular.ttf' })
export { inter, lora, sourceCodePro400, sourceCodePro700, greatVibes }
JavaScript
import { Inter, Lora, Source_Sans_3 } from 'next/font/google'
import localFont from 'next/font/local'
// define your variable fonts
const inter = Inter()
const lora = Lora()
// define 2 weights of a non-variable font
const sourceCodePro400 = Source_Sans_3({ weight: '400' })
const sourceCodePro700 = Source_Sans_3({ weight: '700' })
// define a custom local font where GreatVibes-Regular.ttf is stored in the styles folder
const greatVibes = localFont({ src: './GreatVibes-Regular.ttf' })
export { inter, lora, sourceCodePro400, sourceCodePro700, greatVibes }
现在你可以在代码中按如下方式使用这些定义:
TypeScript
import { inter, lora, sourceCodePro700, greatVibes } from '../styles/fonts'
export default function Page() {
return (
<div>
<p className={inter.className}>Hello world using Inter font</p>
<p style={lora.style}>Hello world using Lora font</p>
<p className={sourceCodePro700.className}>
Hello world using Source_Sans_3 font with weight 700
</p>
<p className={greatVibes.className}>My title in Great Vibes font</p>
</div>
)
}
JavaScript
import { inter, lora, sourceCodePro700, greatVibes } from '../styles/fonts'
export default function Page() {
return (
<div>
<p className={inter.className}>Hello world using Inter font</p>
<p style={lora.style}>Hello world using Lora font</p>
<p className={sourceCodePro700.className}>
Hello world using Source_Sans_3 font with weight 700
</p>
<p className={greatVibes.className}>My title in Great Vibes font</p>
</div>
)
}
为了更轻松地在代码中访问字体定义,你可以在 tsconfig.json 或 jsconfig.json 文件中按如下方式定义路径别名:
{
"compilerOptions": {
"paths": {
"@/fonts": ["./styles/fonts"]
}
}
}
现在你可以按如下方式导入任意字体定义:
TypeScript
import { greatVibes, sourceCodePro400 } from '@/fonts'
JavaScript
import { greatVibes, sourceCodePro400 } from '@/fonts'
预加载
当在网站的某个页面上调用字体函数时,该字体不会全局可用,也不会在所有路由上预加载。相反,该字体仅会根据其使用所在文件的类型,在相关路由上预加载:
版本变更
| 版本 | 变更 |
|---|---|
v13.2.0 |
@next/font 已重命名为 next/font。不再需要安装。 |
v13.0.0 |
新增了 @next/font。 |