紀錄工作經驗、相關知識,解決技術相關問題。

Next

Next.js Image Component 用法:next/image 的 width、fill、sizes、preload 與 remotePatterns 設定

Next.js Image Component 用法:next/image 的 width、fill、sizes、preload 與 remotePatterns 設定 特色圖片

Next.js 的 Image Component(next/image)是擴充 HTML <img> 的內建元件:依裝置寬度產生 srcset、把圖片轉成 WebP 等較小的格式、預設 loading="lazy" 延遲載入,並用 width/height 保留版面空間避免位移。本文以 Next.js 16(範例在 16.4.3、App Router 執行)說明 next/image 的必填 props、fill 與 sizes 如何決定 srcset、首屏圖片該用 preload 還是 fetchPriority,以及 Next.js 16 改變的 qualities 預設值與遠端圖片的 remotePatterns 設定。

next/image 基本寫法

從 next/image import Image,src 與 alt 必填。src 是字串路徑時(例如放在 public 資料夾的圖片),還要同時給 width 與 height:

// app/page.tsx
import Image from 'next/image'

export default function Page() {
  return (
    <Image
      src="/tests/nextjs-image-component/sample.png"
      alt="藍圖風格的測試金字塔示意圖"
      width={672}
      height={448}
    />
  )
}

width 與 height 是圖片的固有尺寸(像素),用途是讓瀏覽器算出長寬比、在圖片下載前先保留空間;圖片實際顯示多大由 CSS 決定。只有兩種情況可以不給:圖片是靜態 import,或使用了 fill。

public 底下的檔案從網站根路徑 / 開始引用,所以 public/tests/nextjs-image-component/sample.png 寫成 /tests/nextjs-image-component/sample.png。

alt 用來描述圖片內容給螢幕閱讀器與搜尋引擎,圖片載入失敗時也會顯示。純裝飾用的圖片寫 alt=""。

輸出的 HTML

上面的元件在瀏覽器中變成這樣的 <img>(為了閱讀,網址參數已換行):

<img alt="藍圖風格的測試金字塔示意圖" loading="lazy" width="672" height="448"
  decoding="async" data-nimg="1" style="color:transparent"
  srcSet="/_next/image?url=%2Ftests%2Fnextjs-image-component%2Fsample.png&amp;w=750&amp;q=75 1x,
          /_next/image?url=%2Ftests%2Fnextjs-image-component%2Fsample.png&amp;w=1920&amp;q=75 2x"
  src="/_next/image?url=%2Ftests%2Fnextjs-image-component%2Fsample.png&amp;w=1920&amp;q=75"/>

可以看到幾件 next/image 自動做的事:

  • loading="lazy":next/image 的 loading 預設是 lazy,圖片接近可視範圍才開始下載;原生 <img> 沒寫 loading 時則是 eager。
  • decoding="async":decoding 預設 async,解碼不阻擋其他內容呈現。
  • srcSet 與 src 都改成 /_next/image?url=...&w=...&q=...:這是 Next.js 內建的圖片最佳化 API(路徑預設 /_next/image),依 w(寬度)與 q(品質)即時縮放、轉檔並快取。
  • 有 width、沒有 sizes 時,srcSet 只有 1x、2x 兩個候選,適合固定尺寸的圖片。

1x 與 2x 的寬度不是直接用 672 和 1344,而是從 deviceSizes 與 imageSizes 合併的清單中,各自找第一個大於等於 width、width × 2 的值。預設清單中 ≥672 的第一個是 750、≥1344 的第一個是 1920,所以得到 w=750 與 w=1920。

靜態 import:自動帶入寬高與模糊預覽

用 import 引入圖片檔,Next.js 會在建置時讀出寬高,width、height 不用自己寫;檔案是 jpg、png、webp 或 avif(非動畫)時也會自動產生 blurDataURL,搭配 placeholder="blur" 在載入期間顯示模糊預覽:

import Image from 'next/image'
import sample from '../../../public/tests/nextjs-image-component/sample.png'

export default function Page() {
  return (
    <Image
      src={sample}
      alt="藍圖風格的測試金字塔示意圖"
      placeholder="blur"
      sizes="100vw"
      style={{ width: '100%', height: 'auto' }}
    />
  )
}

輸出的 <img> 會帶上 width="1344" height="896"(原圖尺寸),style 裡多了一段以 data:image/svg+xml 包住的模糊底圖;圖片網址改指向 /_next/static/media/ 底下加了雜湊的檔名。用 style 自訂寬度時,官方提醒要同時設定 height: 'auto' 才能維持長寬比。

圖片格式與檔案大小:/_next/image 回應

images.formats 預設是 ['image/webp']。Next.js 依請求的 Accept 標頭判斷瀏覽器支援的格式,有符合就輸出 WebP,沒有就回原圖格式。同一個 w=750&q=75 網址,換不同 Accept 標頭請求:

請求的 Accept回應 Content-Type回應大小
image/jxl,image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8(Chrome 156 圖片請求送出的值)image/webp33,322 bytes
image/png,*/*image/png147,969 bytes

原始 PNG 是 1344×896、2,142,577 bytes(約 2.1 MB)。瀏覽器 Accept 有 AVIF 也只拿到 WebP,因為預設設定沒有開 AVIF;要啟用時改成 formats: ['image/avif', 'image/webp'],陣列中排前面的格式優先。在 Next.js 前面另外架 Proxy 或 CDN 自行託管時,要讓它轉送 Accept 標頭,格式判斷才會生效。

下面把測試頁每張圖實際選用的候選、回應格式與大小列出來(以 performance.getEntriesByType('resource') 讀取):

next/image 測試頁:六種寫法的 loading、fetchpriority 屬性,以及瀏覽器實際選用的 w 與 q 參數、回應格式 image/webp 與檔案大小

Next.js 16.4.3 next dev、Chrome 156(Windows 11)、視窗寬 1000px、裝置像素比 1 的結果。a~f 分別對應本文的固定尺寸、靜態 import、fill、preload、eager+fetchPriority、quality 80 範例。

最佳化 API 不接受清單外的參數。直接請求 /_next/image 時,寬度不在 deviceSizes/imageSizes 內、或品質不在 qualities 內,都會回 400:

GET /_next/image?url=%2Ftests%2Fnextjs-image-component%2Fsample.png&w=700&q=75
400 "w" parameter (width) of 700 is not allowed

GET /_next/image?url=%2Ftests%2Fnextjs-image-component%2Fsample.png&w=750&q=80
400 "q" parameter (quality) of 80 is not allowed

fill 與 sizes:響應式圖片

不知道圖片寬高、或要讓圖片填滿容器時,用 fill 取代 width/height。圖片會被設成 position: absolute 撐滿父元素,父元素必須設定 position: relative、fixed 或 absolute;裁切方式用 objectFit 控制:

<div style={{ position: 'relative', width: '100%', aspectRatio: '16 / 9' }}>
  <Image
    src="/tests/nextjs-image-component/sample.png"
    alt="藍圖風格的測試金字塔示意圖"
    fill
    sizes="(max-width: 768px) 100vw, 50vw"
    style={{ objectFit: 'cover' }}
  />
</div>

sizes 告訴瀏覽器圖片在各斷點的顯示寬度,瀏覽器再依此從 srcset 挑選檔案。上例的意思是:視窗寬度 768px 以下時圖片佔滿視窗,其餘情況佔一半。沒有寫 sizes 時,瀏覽器會假設圖片和視窗一樣寬(100vw),可能下載過大的檔案。

sizes 也會改變 Next.js 產生的 srcset:

寫法產生的 srcset
有 width、沒有 sizes只有 1x、2x 兩個候選
fill、沒有 sizes只用 deviceSizes,當作圖片佔滿整個視窗
有 sizes完整的 w 描述子清單(例如 640w、750w…)

有 sizes 時,Next.js 會找出 sizes 裡最小的 vw 百分比,把小於「deviceSizes 最小值 × 該比例」的寬度濾掉。上例最小是 50vw,640 × 0.5 = 320,所以 srcset 從 384 開始:

384w, 640w, 750w, 828w, 1080w, 1200w, 1920w, 2048w, 3840w

視窗寬 1000px、裝置像素比 1 時,50vw 等於 500px,瀏覽器選了 w=640;同一頁 sizes="100vw" 的靜態 import 範例則選了 w=1080(見上方截圖 b、c 兩列)。

srcset 用到的兩組寬度清單預設值如下,可以在 next.config.ts 的 images 改寫:

// next.config.ts(以下是預設值,不設定就是這樣)
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  images: {
    deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
    imageSizes: [32, 48, 64, 96, 128, 256, 384],
  },
}

export default nextConfig

imageSizes 只用在有 sizes 的圖片,代表比螢幕窄的圖片,所以官方建議其中的值都要小於 deviceSizes 的最小值。Next.js 16 從 imageSizes 預設值拿掉了 16,需要 16px 寬的圖片要自己加回去。

srcset 中 w 描述子與 sizes 的計算方式,和原生 <img>/<picture> 相同,細節可以看 HTML picture srcset 與 sizes 效能優化實作:w 描述符計算與 DPR 載入策略。

首屏圖片:preload、loading="eager" 與 fetchPriority

next/image 預設延遲載入,首屏的主圖(hero image)應該立即載入。next dev 會在瀏覽器偵測 Largest Contentful Paint(LCP)元素,LCP 是延遲載入的 next/image 時,Console 出現這段提醒:

Image with src "/tests/nextjs-image-component/sample.png" was detected as the Largest Contentful Paint (LCP). Please add the `loading="eager"` property if this image is above the fold.
Read more: https://nextjs.org/docs/app/api-reference/components/image#loading

這個檢查只在開發模式執行。Next.js 16 提供三種寫法:

{/* 1. preload:在 <head> 插入 <link rel="preload"> */}
<Image src="/hero.png" alt="主視覺" width={320} height={213} preload />

{/* 2. loading="eager":立即載入,不延遲 */}
<Image src="/hero.png" alt="主視覺" width={320} height={213} loading="eager" />

{/* 3. fetchPriority="high":提高下載優先順序(搭配 eager) */}
<Image src="/hero.png" alt="主視覺" width={320} height={213} loading="eager" fetchPriority="high" />

三種寫法輸出的差異:

  • preload(預設 false):<head> 多一行 <link rel="preload" as="image" imageSrcSet="...">,<img> 上不再有 loading 屬性(原生預設即 eager),也沒有加上 fetchpriority。
  • loading="eager":<img loading="eager">,沒有 preload。
  • fetchPriority="high":原樣輸出成 <img fetchpriority="high">。HTML 規格中 fetchpriority 可用 high、low、auto,沒寫或寫錯都視為 auto。要注意只寫 fetchPriority="high" 時,next/image 仍會輸出 loading="lazy",開發模式的 LCP 提醒也照樣出現(它只檢查 loading 是不是 lazy),所以首屏圖片要和 loading="eager" 一起寫。

官方文件的建議是:多數情況用 loading="eager" 或 fetchPriority="high",不用 preload。preload 適合「確定是 LCP 元素的首屏主圖」,以及想在瀏覽器解析到 <body> 之前就開始下載的情況;以下情況不要用:依視窗大小不同、LCP 可能是不同張圖時,或已經用了 loading、fetchPriority 時。

priority 在 Next.js 16 已棄用

Next.js 16 起 priority 已棄用,官方改用意思更明確的 preload。在 16.4.3 中 priority 仍可使用,輸出的 HTML 和 preload 完全相同(<head> 的 preload 連結、<img> 沒有 loading),next dev 與 next build 都沒有出現警告。舊專案升級時,把 priority 改成 preload,或照上面的建議改用 loading="eager"、fetchPriority="high"。

quality 與 images.qualities:Next.js 16 預設只允許 75

quality 是 1~100 的整數,預設 75。Next.js 16 把 images.qualities 的預設值從「允許所有品質」改成只有 [75],官方說明是為了避免有人用任意品質值請求最佳化 API、讓伺服器產生你沒打算提供的版本。

quality 不在 qualities 清單內時,會被換成清單中最接近的值。寫 quality={80},輸出的網址仍是 q=75,開發模式下 next dev 終端機出現這段警告(next build 不會顯示):

Image with src "/tests/nextjs-image-component/sample.png" is using quality "80" which is not configured in images.qualities [75]. Please update your config to [75, 80].
Read more: https://nextjs.org/docs/messages/next-image-unconfigured-qualities

要用其他品質,把值加進 qualities:

// next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  images: {
    qualities: [50, 75, 100],
  },
}

export default nextConfig

這時寫 quality={80} 會換成最接近的 75;直接請求 /_next/image 帶 q=80 則一樣回 400。

遠端圖片:images.remotePatterns 設定

src 是外部網址時,要先在 next.config.ts 的 images.remotePatterns 宣告允許的來源,否則頁面渲染直接失敗。以官方文件的 S3 範例網址為例,沒有設定時 next dev 終端機的錯誤:

⨯ Error: Invalid src prop (https://s3.amazonaws.com/my-bucket/profile.png) on `next/image`, hostname "s3.amazonaws.com" is not configured under images in your `next.config.js`
See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host

頁面回應 500。加上設定後即可正常輸出:

// next.config.ts
import type { NextConfig } from 'next'

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

export default nextConfig
<Image
  src="https://s3.amazonaws.com/my-bucket/profile.png"
  alt="Picture of the author"
  width={500}
  height={500}
/>

遠端圖片在建置時讀不到檔案,所以 width、height(以及要用模糊預覽時的 blurDataURL)都要自己提供,或改用 fill。

remotePatterns 的比對規則:

  • protocol、hostname、port、pathname、search 逐項比對,不符合的請求一律回 400。比對區分大小寫,example.org 和 www.example.org 是不同主機。
  • 萬用字元:* 比對單一路徑段或單一層子網域;** 比對路徑結尾的任意多段,或開頭的任意多層子網域(例如 **.example.com),不能放在中間。
  • 省略 protocol、port、pathname 或 search 時視為 **,官方不建議,因為可能讓別人拿你的伺服器最佳化不相干的圖片。
  • search: '' 表示網址不得帶 query string;要允許特定版本參數時寫完整值,例如 search: '?v=1727111025337'。
  • Next.js 15.3 起,也可以直接寫 URL 物件:remotePatterns: [new URL('https://example.com/account123/**')]。

舊寫法 images.domains 從 Next.js 14 起已棄用,它無法限制 protocol、port、路徑,也不支援萬用字元,改用 remotePatterns。

remotePatterns 只決定最佳化 API 能替哪些外部網址抓圖;改用原生 <img crossorigin> 或在 Canvas 處理外部圖片遇到跨網域錯誤時,可以看 解決 Next.js 中圖片 CORS 問題。

本機圖片帶 query string:localPatterns

Next.js 16 起,本機圖片的 src 帶 query string(例如 /assets/photo?v=1)時,必須在 images.localPatterns 設定對應的 search,否則渲染時丟出錯誤:

Error: Image with src "/tests/nextjs-image-component/sample.png?v=1" is using a query string which is not configured in images.localPatterns.
Read more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns

設定方式:

// next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  images: {
    localPatterns: [
      {
        pathname: '/assets/**',
        search: '?v=1',
      },
    ],
  },
}

export default nextConfig

設定了 localPatterns 之後,只有符合的本機路徑能被最佳化,直接請求其他路徑回 400。<Image> 用到不符合的本機路徑時,頁面渲染也會失敗:只寫上面那一條時,沒有 query string 的 /assets/photo.png 也不符合(search 要完全相同),錯誤訊息是 does not match images.localPatterns configured in your next.config.js。同時有帶與不帶 query string 的圖片時,要再加一條 { pathname: '/assets/**', search: '' }。

onLoad、onError 要在 Client Component 使用

onLoad(圖片載入完成、placeholder 移除後觸發)、onError(載入失敗時觸發)與 loader 這類接收函式的 props,在 App Router 中要放在 Client Component,也就是檔案開頭加 'use client':

'use client'

import Image from 'next/image'

export default function Avatar() {
  return (
    <Image
      src="/tests/nextjs-image-component/sample.png"
      alt="藍圖風格的測試金字塔示意圖"
      width={320}
      height={213}
      onLoad={(e) => console.log((e.target as HTMLImageElement).naturalWidth)}
    />
  )
}

e.target 是實際的 <img> 元素,上例在 Console 印出 384:naturalWidth 是瀏覽器從 srcset 選到的那個最佳化版本(w=384)的寬度,不是原圖的 1344。

在 Server Component 直接傳函式給 onLoad,next build 預先渲染時會失敗:

Error: Event handlers cannot be passed to Client Component props.
  {src: ..., alt: ..., width: 320, height: ..., onLoad: function onLoad}
                                                        ^^^^^^^^^^^^^^^
If you need interactivity, consider converting part of this to a Client Component.

舊的 onLoadingComplete 從 Next.js 14 起已棄用,改用 onLoad。Server Component 與 Client Component 的邊界規則,可以看 Next.js use client 指令用法。

images 設定預設值速查(Next.js 16)

設定預設值說明
deviceSizes[640, 750, 828, 1080, 1200, 1920, 2048, 3840]裝置寬度斷點,用於有 sizes 或 fill 的圖片
imageSizes[32, 48, 64, 96, 128, 256, 384]和 deviceSizes 合併成完整寬度清單;Next.js 16 拿掉 16
qualities[75]允許的品質值;Next.js 16 起預設只有 75
formats['image/webp']可改 ['image/avif', 'image/webp']
minimumCacheTTL14400(4 小時)最佳化結果的快取秒數;Next.js 16 從 60 秒改為 4 小時
maximumRedirects3抓遠端圖片最多跟隨幾次重新導向;Next.js 16 從無限制改為 3
dangerouslyAllowLocalIPfalseNext.js 16 新增,預設禁止最佳化區域網路 IP 的圖片
path'/_next/image'最佳化 API 的路徑
unoptimizedfalse設為 true 時所有圖片原樣輸出,不縮放、不轉檔

SVG 預設不經過最佳化:src 以 .svg 結尾時會自動當成 unoptimized,原檔直接輸出。

參考資料與延伸閱讀

發佈留言