跳至內容

字型優化

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

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

next/font 內建自動自託管功能,適用於任何字體檔案。這表示您可以最佳化網頁字體的載入,且不會造成版面偏移,這要歸功於其底層使用的 CSS size-adjust 屬性。

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

Google Fonts

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

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

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

pages/_app.js
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'] })
 
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> 中套用字體
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 Fonts 會自動進行子集化。這可以減少字體檔案的大小並提升效能。您需要定義要預載的子集。如果在 preloadtrue 時未指定任何子集,將會產生警告。

您可以透過將其添加到函式呼叫中來完成此操作

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

在上面的範例中,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 樣式。

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

本地字體 可變字體以獲得最佳效能和彈性。

pages/_app.js
import localFont from 'next/font/local'
 
// Font files can be colocated inside of `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

透過Tailwind CSSCSS 變數,可以使用 next/font

在下面的例子中,我們使用來自 next/font/googleInter 字體(您可以使用任何來自 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 字體函式時,該字體都會在您的應用程式中作為一個執行個體託管。因此,如果您在多個檔案中載入相同的字體函式,則會託管同一個字體的多個執行個體。在這種情況下,建議執行以下操作:

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