如何使用字體

next/font 模組會自動優化您的字體並移除外部網路請求,從而提高隱私性和效能。

它包含內建的自我託管功能,適用於任何字體檔案。這意味著您可以最佳化載入網頁字體,且不會發生版面位移 (layout shift)。

要開始使用 next/font,請從 next/font/localnext/font/google 匯入它,將其作為函式呼叫並設定適當的選項,然後為您想要應用字體的元素設定 className。例如:

import { Geist } from 'next/font/google'

const geist = Geist({
  subsets: ['latin'],
})

export default function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={geist.className}>
      <body>{children}</body>
    </html>
  )
}

字體的作用範圍僅限於使用它們的元件。若要將字體套用至整個應用程式,請將其新增至 根佈局 (Root Layout)

Google 字體

您可以自動自我託管任何 Google 字體。字體會作為靜態資源儲存,並從與您的部署相同的網域提供服務,這意味著使用者造訪您的網站時,瀏覽器不會向 Google 發送任何請求。

要開始使用 Google 字體,請從 next/font/google 匯入您選擇的字體:

import { Geist } from 'next/font/google'

const geist = Geist({
  subsets: ['latin'],
})

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className={geist.className}>
      <body>{children}</body>
    </html>
  )
}

我們建議使用 可變字體 (variable fonts) 以獲得最佳效能和靈活性。但如果您無法使用可變字體,則需要指定字重 (weight):

import { Roboto } from 'next/font/google'

const roboto = Roboto({
  weight: '400',
  subsets: ['latin'],
})

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className={roboto.className}>
      <body>{children}</body>
    </html>
  )
}

本地字體

要使用本地字體,請從 next/font/local 匯入您的字體,並指定本地字體檔案的 src。字體可以儲存在 public 資料夾中。例如:

import localFont from 'next/font/local'

const myFont = localFont({
  src: './my-font.woff2',
})

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',
    },
  ],
})

On this page