字体模块
next/font 会自动优化你的字体(包括自定义字体),并移除外部网络请求以提高隐私性和性能。
它包含内置的自动自托管功能,适用于任何字体文件。这意味着你可以在没有布局偏移的情况下优化加载网页字体。
你还可以方便地使用所有 Google Fonts。CSS 和字体文件会在构建时下载,并与你的其余静态资源一起自托管。浏览器不会向 Google 发送任何请求。
要在所有页面中使用字体,请将其添加到 /pages 下的 _app.js 文件中,如下所示:
import { Inter } from 'next/font/google'
// 如果加载可变字体,你不需要指定字体粗细
const inter = Inter({ subsets: ['latin'] })
export default function MyApp({ Component, pageProps }) {
return (
<main className={inter.className}>
<Component {...pageProps} />
</main>
)
}🎥 观看: 了解更多关于使用
next/font的内容 → YouTube(6分钟)。
参考
| 键 | font/google | font/local | 类型 | 必需 |
|---|---|---|---|---|
src | String or Array of Objects | 是 | ||
weight | String or Array | 必需/可选 | ||
style | String or Array | - | ||
subsets | Array of Strings | - | ||
axes | Array of Strings | - | ||
display | String | - | ||
preload | Boolean | - | ||
fallback | Array of Strings | - | ||
adjustFontFallback | Boolean or String | - | ||
variable | String | - | ||
declarations | Array of Objects | - |
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 指定的字体将在头部注入预加载链接标签。
在 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。
在 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。
在 next/font/local 中使用
- 可选
示例:
declarations: [{ prop: 'ascent-override', value: '90%' }]
示例
Google Fonts
要使用 Google 字体,请从 next/font/google 将其作为函数导入。我们建议使用可变字体以获得最佳性能和灵活性。
要在所有页面中使用字体,请将其添加到 /pages 下的 _app.js 文件中,如下所示:
import { Inter } from 'next/font/google'
// 如果加载可变字体,你不需要指定字体粗细
const inter = Inter({ subsets: ['latin'] })
export default function MyApp({ Component, pageProps }) {
return (
<main className={inter.className}>
<Component {...pageProps} />
</main>
)
}如果你无法使用可变字体,你将需要指定粗细:
import { Roboto } from 'next/font/google'
const roboto = Roboto({
weight: '400',
subsets: ['latin'],
})
export default function MyApp({ Component, pageProps }) {
return (
<main className={roboto.className}>
<Component {...pageProps} />
</main>
)
}你可以使用数组指定多个粗细和/或样式:
const roboto = Roboto({
weight: ['400', '700'],
style: ['normal', 'italic'],
subsets: ['latin'],
display: 'swap',
})值得注意的是:对于有多个单词的字体名称使用下划线(_)。例如,
Roboto Mono应导入为Roboto_Mono。
在 <head> 中应用字体
你还可以在不使用包装器和 className 的情况下通过将其注入到 <head> 中来使用字体,如下所示:
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
export default function MyApp({ Component, pageProps }) {
return (
<>
<style jsx global>{`
html {
font-family: ${inter.style.fontFamily};
}
`}</style>
<Component {...pageProps} />
</>
)
}单页使用
要在单个页面上使用字体,请将其添加到特定页面,如下所示:
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
export default function Home() {
return (
<div className={inter.className}>
<p>Hello World</p>
</div>
)
}指定子集
Google Fonts 会自动进行子集化。这会减小字体文件的大小并提高性能。你需要定义要预加载这些子集中的哪些。在 preload 为 true 时未能指定任何子集将导致警告。
这可以通过将其添加到函数调用中来完成:
const inter = Inter({ subsets: ['latin'] })查看 Font API 参考了解更多信息。
使用多个字体
你可以在应用程序中导入和使用多个字体。有两种方法可以采用。
第一种方法是创建一个实用函数,该函数导出字体、导入它并在需要的地方应用其 className。这可确保字体仅在渲染时预加载:
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',
})在上面的示例中,Inter 将全局应用,而 Roboto Mono 可以根据需要导入和应用。
或者,你可以创建一个 CSS 变量并将其与你喜欢的 CSS 解决方案一起使用:
html {
font-family: var(--font-inter);
}
h1 {
font-family: var(--font-roboto-mono);
}在上面的示例中,Inter 将全局应用,任何 <h1> 标签将使用 Roboto Mono 进行样式设置。
建议:谨慎使用多个字体,因为每个新字体都是客户端必须下载的额外资源。
本地字体
导入 next/font/local 并指定本地字体文件的 src。我们建议使用可变字体以获得最佳性能和灵活性。
import localFont from 'next/font/local'
// 字体文件可以放在 `pages` 内部
const myFont = localFont({ src: './my-font.woff2' })
export default function MyApp({ Component, pageProps }) {
return (
<main className={myFont.className}>
<Component {...pageProps} />
</main>
)
}如果你想为单个字体系列使用多个文件,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>标签。
import { Inter } from 'next/font/google'
const inter = Inter({
subsets: ['latin'],
variable: '--font-inter',
})
const roboto_mono = Roboto_Mono({
subsets: ['latin'],
display: 'swap',
variable: '--font-roboto-mono',
})
export default function MyApp({ Component, pageProps }) {
return (
<main className={`${inter.variable} ${roboto_mono.variable} font-sans`}>
<Component {...pageProps} />
</main>
)
}最后,将 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 选项:
import { Inter } from 'next/font/google'
import styles from '../styles/component.module.css'
const inter = Inter({
variable: '--font-inter',
})要使用字体,请将要设置样式的文本的父容器的 className 设置为字体加载器的 variable 值,并将文本的 className 设置为外部 CSS 文件中的 styles 属性。
<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 文件。
然后,按如下方式指定字体定义:
import { Inter, Lora, Source_Sans_3 } from 'next/font/google'
import localFont from 'next/font/local'
// 定义你的可变字体
const inter = Inter()
const lora = Lora()
// 定义非可变字体的 2 个粗细
const sourceCodePro400 = Source_Sans_3({ weight: '400' })
const sourceCodePro700 = Source_Sans_3({ weight: '700' })
// 定义一个自定义本地字体,其中 GreatVibes-Regular.ttf 存储在 styles 文件夹中
const greatVibes = localFont({ src: './GreatVibes-Regular.ttf' })
export { inter, lora, sourceCodePro400, sourceCodePro700, greatVibes }你现在可以在代码中按如下方式使用这些定义:
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"]
}
}
}你现在可以按如下方式导入任何字体定义:
import { greatVibes, sourceCodePro400 } from '@/fonts'预加载
当在你网站的页面上调用字体函数时,它不会全局可用并在所有路由上预加载。相反,字体仅根据使用它的文件类型在相关路由上预加载:
版本变更
| 版本 | 变更 |
|---|---|
v13.2.0 | @next/font 重命名为 next/font。不再需要安装。 |
v13.0.0 | 引入 @next/font。 |