静态资源 (Static Assets)

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" />
}

缓存机制

由于 public 文件夹中的资源可能会发生变化,Next.js 无法安全地缓存这些资源。默认应用的缓存头是:

Cache-Control: public, max-age=0

机器人协议、网站图标及其他

该文件夹还可用于存放 robots.txtfavicon.ico、Google 网站验证文件以及其他静态文件(包括 .html)。但请确保不要存在与 pages/ 目录中文件同名的静态文件,否则会导致错误。了解更多

须知:

  • 目录必须命名为 public。该名称不可更改,并且是唯一用于托管静态资源的目录。
  • 只有构建时存在于 public 目录中的资源才会被 Next.js 托管。请求时添加的文件将不可用。我们建议使用第三方服务(如 Vercel Blob)进行持久化文件存储。

On this page