favicon、icon 和 apple-icon
favicon
、icon
或 apple-icon
文件约定允许你为应用程序设置图标。
这些图标在网页浏览器标签、手机主屏幕和搜索引擎结果等地方显示时非常有用。
设置应用程序图标有两种方式:
图像文件 (.ico, .jpg, .png)
要使用图像文件设置应用程序图标,只需将 favicon
、icon
或 apple-icon
图像文件放在 /app
目录中。
favicon
图像只能位于 app/
的顶层。
Next.js 将评估该文件并自动将适当的标签添加到你的应用程序的 <head>
元素中。
文件约定 | 支持的文件类型 | 有效位置 |
---|---|---|
favicon | .ico | app/ |
icon | .ico 、.jpg 、.jpeg 、.png 、.svg | app/**/* |
apple-icon | .jpg 、.jpeg 、.png | app/**/* |
favicon
在根 /app
路由段中添加 favicon.ico
图像文件。
icon
添加 icon.(ico|jpg|jpeg|png|svg)
图像文件。
apple-icon
添加 apple-icon.(jpg|jpeg|png)
图像文件。
要点
- 你可以通过在文件名后添加数字后缀来设置多个图标。例如,
icon1.png
、icon2.png
等。带数字的文件将按字典序排序。- Favicon 只能在根
/app
段中设置。如果你需要更细粒度的控制,可以使用icon
。- 适当的
<link>
标签和属性(如rel
、href
、type
和sizes
)是根据图标类型和评估文件的元数据确定的。
- 例如,32 x 32 像素的
.png
文件将具有type="image/png"
和sizes="32x32"
属性。sizes="any"
被添加到favicon.ico
输出中,以避免浏览器 bug,该 bug 会导致.ico
图标优先于.svg
。
使用代码生成图标 (.js, .ts, .tsx)
除了使用实际图像文件外,你还可以使用代码以编程方式生成图标。
通过创建默认导出函数的 icon
或 apple-icon
路由来生成应用程序图标。
文件约定 | 支持的文件类型 |
---|---|
icon | .js 、.ts 、.tsx |
apple-icon | .js 、.ts 、.tsx |
生成图标最简单的方法是使用 next/og
中的 ImageResponse
API。
要点
- 默认情况下,生成的图标是静态优化的 (在构建时生成并缓存),除非它们使用动态函数或未缓存的数据。
- 你可以使用
generateImageMetadata
在同一文件中生成多个图标。- 你无法生成
favicon
图标。请使用icon
或 favicon.ico 文件代替。- 应用程序图标是特殊的路由处理程序,默认情况下会被缓存,除非它使用动态函数或动态配置选项。
Props
默认导出函数接收以下 props:
params
(可选)
一个包含从根段到 icon
或 apple-icon
所在段的动态路由参数对象。
路由 | URL | params |
---|---|---|
app/shop/icon.js | /shop | undefined |
app/shop/[slug]/icon.js | /shop/1 | { slug: '1' } |
app/shop/[tag]/[item]/icon.js | /shop/1/2 | { tag: '1', item: '2' } |
返回值
默认导出函数应返回 Blob
| ArrayBuffer
| TypedArray
| DataView
| ReadableStream
| Response
。
要点:
ImageResponse
满足这个返回类型。
配置导出
你可以通过从 icon
或 apple-icon
路由导出 size
和 contentType
变量来选择性地配置图标的元数据。
选项 | 类型 |
---|---|
size | { width: number; height: number } |
contentType | string - 图像 MIME 类型 |
size
contentType
路由段配置
icon
和 apple-icon
是专门的路由处理程序,可以使用与页面和布局相同的路由段配置选项。
版本历史
版本 | 变更 |
---|---|
v13.3.0 | 引入 favicon 、icon 和 apple-icon |