跳到內容

字型模組

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