跳到内容

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