圖片優化

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

  • 尺寸優化: 自動為每種裝置提供正確尺寸的圖片,使用 WebP 等現代圖片格式。
  • 視覺穩定性: 在圖片載入時自動防止版面位移 (layout shift)
  • 更快的頁面載入: 僅在圖片進入視窗時載入,使用瀏覽器原生的延遲載入,並可選擇模糊預覽圖。
  • 資源靈活性: 按需調整圖片大小,即使是遠端伺服器上的圖片也能處理。

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

import Image from 'next/image'

export default function Page() {
  return <Image src="" alt="" />
}

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

🎥 觀看影片: 了解更多關於如何使用 next/imageYouTube (9 分鐘)

本地圖片

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

顯示 app 和 public 資料夾的目錄結構
import Image from 'next/image'

export default function Page() {
  return (
    <Image
      src="/profile.png"
      alt="作者的照片"
      width={500}
      height={500}
    />
  )
}

靜態導入圖片

您也可以導入並使用本地圖片檔案。Next.js 會根據導入的檔案自動確定圖片的固有 widthheight。這些值用於確定圖片比例,並在圖片載入時防止累積版面位移 (Cumulative Layout Shift)

import Image from 'next/image'
import ProfileImage from './profile.png'

export default function Page() {
  return (
    <Image
      src={ProfileImage}
      alt="作者的照片"
      // width={500} 自動提供
      // height={500} 自動提供
      // blurDataURL="data:..." 自動提供
      // placeholder="blur" // 可選的載入時模糊效果
    />
  )
}

在這種情況下,Next.js 會預期 app/profile.png 檔案是可用的。

遠端圖片

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

import Image from 'next/image'

export default function Page() {
  return (
    <Image
      src="https://s3.amazonaws.com/my-bucket/profile.png"
      alt="作者的照片"
      width={500}
      height={500}
    />
  )
}

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

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

import type { NextConfig } from 'next'

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

export default config

On this page