跳到內容
App Router入門影像最佳化

影像最佳化

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 屬性可以是 本地遠端 影像。

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

本地影像

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

Folder structure showing app and public folders
app/page.tsx
import Image from 'next/image'
 
export default function Page() {
  return (
    <Image
      src="/profile.png"
      alt="Picture of the author"
      width={500}
      height={500}
    />
  )
}

如果影像是靜態匯入的,Next.js 將自動確定其固有 widthheight。這些值用於確定影像比例並防止影像載入時發生 累積佈局偏移

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

遠端影像

要使用遠端影像,您可以為 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 用於推斷影像的正確寬高比,並避免影像載入時發生佈局偏移。或者,您可以使用 fill 屬性使影像填充父元素的大小。

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

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

API 參考

請參閱 API 參考以獲取 Next.js Image 的完整功能集。