跳到內容
App Router入門字型最佳化

字型最佳化

next/font 模組會自動最佳化你的字型,並消除外部網路請求,以提高隱私和效能。

它為任何字型檔案提供了內建的自託管。這意味著你可以以最佳方式載入網路字型,且不會出現佈局偏移。

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

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

字型的作用域限定在其使用的元件中。要將字型應用於整個應用程式,請將其新增到根佈局

Google 字型

你可以自動自託管任何 Google 字型。字型作為靜態資產儲存,並從與你的部署相同的域提供,這意味著使用者訪問你的網站時,瀏覽器不會向 Google 傳送請求。

要開始使用 Google 字型,請從 next/font/google 匯入你選擇的字型。

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

我們建議使用可變字型以獲得最佳效能和靈活性。但如果你不能使用可變字型,你需要指定字型粗細。

app/layout.tsx
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資料夾中,或與 app 資料夾共同放置。例如

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

API 參考

請參閱 API 參考,瞭解 Next.js 字型的完整功能集