跳到主要内容

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/ 目录中的文件同名的静态文件,因为这会导致错误。了解更多

对于静态元数据文件,如 robots.txtfavicon.ico 等,你应该在 app 文件夹内使用特殊元数据文件