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.txtfavicon.ico、Google 网站验证文件以及其他静态文件(包括 .html)。但请注意不要使静态文件与 pages/ 目录中的文件同名,否则会导致错误。了解更多

On this page