跳到内容

字体模块

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

它包含针对任何字体文件的**内置自动自托管**。这意味着你可以以最佳方式加载网页字体,而不会出现布局偏移

你还可以方便地使用所有Google 字体。CSS 和字体文件会在构建时下载,并与你的其他静态资源一起自托管。**浏览器不会向 Google 发送任何请求。**

app/layout.tsx
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>
  )
}

🎥 观看: 了解更多关于使用 next/fontYouTube(6 分钟)

参考

font/googlefont/local类型必需
src字符串或对象数组
字重字符串或数组必填/可选
style字符串或数组-
子集字符串数组-
字符串数组-
显示字符串-
预加载布尔值-
回退字符串数组-
调整字体回退布尔值或字符串-
变量字符串-
声明对象数组-

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/googlenext/font/local 中使用

  • 如果正在使用的字体**不是**可变字体,则为必填项

示例

  • weight: '400':单个字重值的字符串 - 对于字体Inter,可能的值是 '100''200''300''400''500''600''700''800''900''variable'(其中 'variable' 是默认值)
  • weight: '100 900':可变字体 100900 范围的字符串
  • weight: ['100','400','900']:非可变字体的 3 个可能值数组

style

字体style,可能的值如下

  • 字符串,默认值为 'normal'
  • 如果字体不是可变 Google 字体,则为样式值数组。仅适用于 next/font/google

next/font/googlenext/font/local 中使用

  • 可选

示例

  • style: 'italic':一个字符串 - 对于 next/font/google,可以是 normalitalic
  • style: 'oblique':一个字符串 - 对于 next/font/local 可以是任何值,但预期来自标准字体样式
  • style: ['italic','normal']:对于 next/font/google 的 2 个值数组 - 这些值来自 normalitalic

subsets

字体subsets由一个字符串值数组定义,其中包含你希望预加载的每个子集的名称。通过 subsets 指定的字体,当preload选项为 true(默认值)时,头部将注入一个链接预加载标签。

next/font/google 中使用

  • 可选

示例

  • subsets: ['latin']:包含子集 latin 的数组

你可以在你的字体的 Google 字体页面上找到所有子集的列表。

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/googlenext/font/local 中使用

  • 可选

示例

  • display: 'optional':一个分配给 optional 值的字符串

preload

一个布尔值,指定是否应该预加载字体。默认值为 true

next/font/googlenext/font/local 中使用

  • 可选

示例

  • preload: false

fallback

如果字体无法加载,则使用回退字体。回退字体是一个字符串数组,没有默认值。

  • 可选

next/font/googlenext/font/local 中使用

示例

  • fallback: ['system-ui', 'arial']:将回退字体设置为 system-uiarial 的数组

adjustFontFallback

next/font/googlenext/font/local 中使用

  • 可选

示例

  • adjustFontFallback: false:适用于 next/font/google
  • adjustFontFallback: 'Times New Roman':适用于 next/font/local

variable

一个字符串值,用于定义如果使用CSS 变量方法应用样式时要使用的 CSS 变量名。

next/font/googlenext/font/local 中使用

  • 可选

示例

  • variable: '--my-font':声明了 CSS 变量 --my-font

declarations

字体面描述符键值对数组,用于进一步定义生成的 @font-face

next/font/local 中使用

  • 可选

示例

  • 声明:[{ prop: 'ascent-override', value: '90%' }]

示例

Google 字体

要使用 Google 字体,请从 next/font/google 中将其作为函数导入。我们建议使用可变字体以获得最佳性能和灵活性。

app/layout.tsx
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>
  )
}

如果不能使用可变字体,你将**需要指定一个字重**

app/layout.tsx
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>
  )
}

你可以通过使用数组来指定多个字重和/或样式

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

须知:对于多词字体名称,请使用下划线 (_)。例如,Roboto Mono 应导入为 Roboto_Mono

指定子集

Google 字体会自动子集化。这会减小字体文件大小并提高性能。你需要定义要预加载的子集。如果在 preloadtrue 的情况下未指定任何子集,则会发出警告。

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

app/layout.tsx
const inter = Inter({ subsets: ['latin'] })

有关更多信息,请参阅字体 API 参考

使用多种字体

你可以在你的应用程序中导入和使用多种字体。有两种方法可以实现。

第一种方法是创建一个实用函数,该函数导出字体,然后导入并应用其 className 到需要的地方。这可以确保字体仅在渲染时才预加载

app/fonts.ts
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',
})
app/layout.tsx
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>
  )
}
app/page.tsx
import { roboto_mono } from './fonts'
 
export default function Page() {
  return (
    <>
      <h1 className={roboto_mono.className}>My page</h1>
    </>
  )
}

在上面的示例中,Inter 将全局应用,而 Roboto Mono 可以按需导入和应用。

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

app/layout.tsx
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>
  )
}
app/global.css
html {
  font-family: var(--font-inter);
}
 
h1 {
  font-family: var(--font-roboto-mono);
}

在上面的例子中,Inter 将全局应用,而任何

标签都将使用 Roboto Mono 样式。

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

本地字体

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

app/layout.tsx
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>
  )
}

如果要为一个字体系列使用多个文件,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',
    },
  ],
})

有关更多信息,请参阅字体 API 参考

与 Tailwind CSS 配合使用

next/font 使用CSS 变量Tailwind CSS 无缝集成。

在下面的示例中,我们使用 next/font/google 中的 InterRoboto_Mono 字体(你可以使用任何 Google 字体或本地字体)。使用 variable 选项为这些字体分别定义 CSS 变量名称,例如 interroboto_mono。然后,应用 inter.variableroboto_mono.variable 将 CSS 变量包含在你的 HTML 文档中。

须知:你可以根据你的偏好、样式需求或项目要求,将这些变量添加到 标签中。

app/layout.tsx
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>
  )
}

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

global.css
@import 'tailwindcss';
 
@theme inline {
  --font-sans: var(--font-inter);
  --font-mono: var(--font-roboto-mono);
}

Tailwind CSS v3

tailwind.config.js
/** @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 实用类将字体应用于你的元素。

<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 对象,包括 style.fontFamily 以访问字体系列名称和回退字体。

<p style={inter.style}>Hello World</p>

CSS 变量

如果你想在外部样式表中设置样式并指定其他选项,请使用 CSS 变量方法。

除了导入字体,还要导入定义 CSS 变量的 CSS 文件,并按如下方式设置字体加载器对象的变量选项

app/page.tsx
import { Inter } from 'next/font/google'
import styles from '../styles/component.module.css'
 
const inter = Inter({
  variable: '--font-inter',
})

要使用该字体,请将要样式化文本的父容器的 className 设置为字体加载器的 variable 值,并将文本的 className 设置为外部 CSS 文件中的 styles 属性。

app/page.tsx
<main className={inter.variable}>
  <p className={styles.text}>Hello World</p>
</main>

component.module.css CSS 文件中定义 text 选择器类如下

styles/component.module.css
.text {
  font-family: var(--font-inter);
  font-weight: 200;
  font-style: italic;
}

在上面的示例中,文本“Hello World”使用 Inter 字体和生成的字体回退进行样式设置,字重为 200,字体样式为斜体。

使用字体定义文件

每次调用 localFont 或 Google 字体函数时,该字体都将作为应用程序中的一个实例进行托管。因此,如果你需要在多个地方使用相同的字体,你应该在一个地方加载它,并在需要的地方导入相关的字体对象。这是通过字体定义文件完成的。

例如,在你的应用根目录下的 styles 文件夹中创建一个 fonts.ts 文件。

然后,按如下方式指定您的字体定义

styles/fonts.ts
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 }

你现在可以在你的代码中按如下方式使用这些定义

app/page.tsx
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.jsonjsconfig.json 文件中定义路径别名,如下所示

tsconfig.json
{
  "compilerOptions": {
    "paths": {
      "@/fonts": ["./styles/fonts"]
    }
  }
}

你现在可以按如下方式导入任何字体定义

app/about/page.tsx
import { greatVibes, sourceCodePro400 } from '@/fonts'

预加载

当在你的网站页面上调用字体函数时,它不会全局可用并在所有路由上预加载。相反,字体仅根据其所用文件的类型在相关路由上预加载

  • 如果是一个单独页面,则会在该页面的单独路由上预加载。
  • 如果这是一个布局,它会在该布局所包裹的所有路由上预加载。
  • 如果是根布局,它会在所有路由上预加载。

版本变更

版本更改
v13.2.0@next/font 已更名为 next/font。不再需要安装。
v13.0.0添加了 @next/font