字體優化

next/font 會自動優化您的字體(包括自訂字體),並移除外部網路請求以提升隱私和效能。

🎥 觀看影片: 深入了解如何使用 next/fontYouTube (6分鐘)

next/font 包含內建的自動自我託管功能,適用於_任何_字體檔案。這意味著您可以透過底層 CSS 的 size-adjust 屬性,以零版面位移的方式最佳化載入網頁字體。

這個新的字體系統還讓您能方便地使用所有 Google 字體,同時兼顧效能和隱私。CSS 和字體檔案會在建置時下載,並與其他靜態資源一起自我託管。瀏覽器不會向 Google 發送任何請求。

Google 字體

自動自我託管任何 Google 字體。字體會包含在部署中,並從與您的部署相同的網域提供服務。瀏覽器不會向 Google 發送任何請求。

首先從 next/font/google 匯入您想使用的字體作為函式。我們建議使用可變字體以獲得最佳效能和靈活性。

要在所有頁面中使用字體,請將其新增至 /pages 下的 _app.js 檔案,如下所示:

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>
  )
}

如果無法使用可變字體,您需要指定字重

pages/_app.js
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>
  )
}

您可以透過陣列指定多個字重和/或樣式:

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

小提示: 對於包含多個單詞的字體名稱,請使用下劃線 (_)。例如,Roboto Mono 應匯入為 Roboto_Mono

<head> 中套用字體

您也可以不使用包裹器和 className,而是透過以下方式將字體注入 <head>

pages/_app.js
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} />
    </>
  )
}

單頁使用

要在單一頁面上使用字體,請將其新增至特定頁面,如下所示:

pages/index.js
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 字體會自動子集化。這可以減少字體檔案的大小並提升效能。您需要定義要預載入哪些子集。如果在 preloadtrue 時未指定任何子集,將會產生警告。

這可以透過將其新增至函式呼叫來完成:

pages/_app.js
const inter = Inter({ subsets: ['latin'] })

查看字體 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 解決方案一起使用:

app/global.css
html {
  font-family: var(--font-inter);
}

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

在上面的範例中,Inter 將全域套用,而任何 <h1> 標籤將使用 Roboto Mono 樣式。

建議: 保守使用多種字體,因為每種新字體都是客戶端需要下載的額外資源。

本地字體

匯入 next/font/local 並指定本地字體檔案的 src。我們建議使用可變字體以獲得最佳效能和靈活性。

pages/_app.js
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',
    },
  ],
})

查看字體 API 參考以獲取更多資訊。

與 Tailwind CSS 一起使用

next/font 可以透過 CSS 變數Tailwind CSS 一起使用。

在下面的範例中,我們使用來自 next/font/google 的字體 Inter(您可以使用來自 Google 或本地字體的任何字體)。使用 variable 選項載入您的字體以定義 CSS 變數名稱並將其分配給 inter。然後,使用 inter.variable 將 CSS 變數新增至您的 HTML 文件。

pages/_app.js
import { Inter } from 'next/font/google'

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

export default function MyApp({ Component, pageProps }) {
  return (
    <main className={`${inter.variable} font-sans`}>
      <Component {...pageProps} />
    </main>
  )
}

最後,將 CSS 變數新增至您的 Tailwind CSS 設定

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 工具類別將字體套用至您的元素。

預載入

當在您網站的頁面上呼叫字體函式時,它不會全域可用,也不會在所有路由上預載入。相反,字體僅根據使用它的檔案類型在相關路由上預載入:

  • 如果是唯一頁面,則在該頁面的唯一路由上預載入。
  • 如果在自訂 App 中,則在 /pages 下的所有網站路由上預載入。

重複使用字體

每次您呼叫 localFont 或 Google 字體函式時,該字體都會作為一個實例託管在您的應用程式中。因此,如果您在多個檔案中載入相同的字體函式,則會託管相同字體的多個實例。在這種情況下,建議執行以下操作:

  • 在一個共享檔案中呼叫字體載入器函式
  • 將其匯出為常數
  • 在每個需要使用此字體的檔案中匯入該常數

On this page