public 資料夾

Next.js 可以在根目錄下的 public 資料夾中提供靜態檔案,例如圖片。public 內的檔案可以透過從基礎 URL (/) 開始的路徑在程式碼中引用。

例如,檔案 public/avatars/me.png 可以透過訪問 /avatars/me.png 路徑來查看。顯示該圖片的程式碼可能如下:

avatar.js
import Image from 'next/image'

export function Avatar({ id, alt }) {
  return <Image src={`/avatars/${id}.png`} alt={alt} width="64" height="64" />
}

export function AvatarOfMe() {
  return <Avatar id="me" alt="A portrait of me" />
}

快取

Next.js 無法安全地快取 public 資料夾中的資源,因為它們可能會變更。預設套用的快取標頭為:

Cache-Control: public, max-age=0

Robots、Favicon 及其他檔案

對於靜態元資料檔案,例如 robots.txtfavicon.ico 等,您應該在 app 資料夾中使用特殊元資料檔案

On this page