Skip to main content

`public` 中的静态资源

Next.js 可以在根目录中名为 public 的文件夹下提供静态文件,例如图片。然后,你的代码可以从基本 URL (/) 开始引用 public 内的文件。

¥Next.js can serve static files, like images, under a folder called public in the root directory. Files inside public can then be referenced by your code starting from the base URL (/).

例如,访问 /avatars/me.png 路径可以查看文件 public/avatars/me.png。显示该图片的代码可能如下所示:

¥For example, the file public/avatars/me.png can be viewed by visiting the /avatars/me.png path. The code to display that image might look like:

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

缓存

¥Caching

Next.js 无法安全地将资源缓存在 public 文件夹中,因为它们可能会发生变化。应用的默认缓存标头是:

¥Next.js cannot safely cache assets in the public folder because they may change. The default caching headers applied are:

Cache-Control: public, max-age=0

机器人、网站图标等

¥Robots, Favicons, and others

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

¥For static metadata files, such as robots.txt, favicon.ico, etc, you should use special metadata files inside the app folder.

很高兴知道:

¥Good to know:

  • 该目录必须命名为 public。该名称无法更改,并且它是用于提供静态资源的唯一目录。

    ¥The directory must be named public. The name cannot be changed and it's the only directory used to serve static assets.

  • 只有位于 构建时间public 目录中的资源才会由 Next.js 提供服务。在请求时添加的文件将不可用。我们建议使用 维塞尔斑点 等第三方服务来进行持久文件存储。

    ¥Only assets that are in the public directory at build time will be served by Next.js. Files added at request time won't be available. We recommend using a third-party service like Vercel Blob for persistent file storage.