跳到內容

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、Favicons 及其他

該資料夾對於 robots.txtfavicon.ico、Google 網站驗證和任何其他靜態檔案(包括 .html)也很有用。但請確保不要有一個與 pages/ 目錄中的檔案同名的靜態檔案,因為這會導致錯誤。閱讀更多