跳到主要內容
App Router開始使用圖片和字體

如何最佳化圖片和字體

Next.js 內建自動圖片和字體最佳化功能,以提升效能和使用者體驗。本頁面將引導您開始使用它們。

處理靜態資源

您可以將靜態檔案(例如圖片和字體)儲存在根目錄中名為 public 的資料夾下。然後,您的程式碼可以從基礎 URL (/) 開始引用 public 內的檔案。

Folder structure showing app and public folders

最佳化圖片

Next.js 的 <Image> 元件擴展了 HTML <img> 元素,以提供:

  • 尺寸最佳化: 自動為每個裝置提供正確尺寸的圖片,並使用現代圖片格式(如 WebP)。
  • 視覺穩定性: 防止圖片載入時自動發生版面配置位移
  • 更快的頁面載入速度: 僅在圖片進入視窗時才使用原生瀏覽器延遲載入,並可選用模糊佔位符。
  • 資源彈性: 隨需調整圖片大小,即使是儲存在遠端伺服器上的圖片。

要開始使用 <Image>,請從 next/image 匯入它,並在您的元件中渲染它。

app/page.tsx
import Image from 'next/image'
 
export default function Page() {
  return <Image src="" alt="" />
}

src 屬性可以是本地遠端圖片。

本地圖片

要使用本地圖片,請從您的public 資料夾匯入您的 .jpg.png.webp 圖片檔案。

app/page.tsx
import Image from 'next/image'
import profilePic from './me.png'
 
export default function Page() {
  return (
    <Image
      src={profilePic}
      alt="Picture of the author"
      // width={500} automatically provided
      // height={500} automatically provided
      // blurDataURL="data:..." automatically provided
      // placeholder="blur" // Optional blur-up while loading
    />
  )
}

Next.js 將根據匯入的檔案自動判斷您圖片的內在widthheight。這些值用於確定圖片比例,並防止圖片載入時發生累計版面配置位移

遠端圖片

要使用遠端圖片,您可以為 src 屬性提供 URL 字串。

app/page.tsx
import Image from 'next/image'
 
export default function Page() {
  return (
    <Image
      src="https://s3.amazonaws.com/my-bucket/profile.png"
      alt="Picture of the author"
      width={500}
      height={500}
    />
  )
}

由於 Next.js 在建置過程中無法存取遠端檔案,因此您需要手動提供 widthheight 和可選的 blurDataURL 屬性。widthheight 屬性用於推斷圖片的正確長寬比,並避免圖片載入時發生版面配置位移。

然後,為了安全地允許來自遠端伺服器的圖片,您需要在 next.config.js 中定義支援的 URL 模式清單。請盡可能明確,以防止惡意使用。例如,以下設定僅允許來自特定 AWS S3 儲存貯體的圖片:

next.config.ts
import { NextConfig } from 'next'
 
const config: NextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 's3.amazonaws.com',
        port: '',
        pathname: '/my-bucket/**',
        search: '',
      },
    ],
  },
}
 
export default config

最佳化字體

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 匯入您的字體,並在public 資料夾中指定本地字體檔案的 src

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