generateMetadata
此页面涵盖了 generateMetadata
和静态元数据对象的所有基于配置的元数据选项。
¥This page covers all Config-based Metadata options with generateMetadata
and the static metadata object.
import type { Metadata } from 'next'
// either Static metadata
export const metadata: Metadata = {
title: '...',
}
// or Dynamic metadata
export async function generateMetadata({ params }) {
return {
title: '...',
}
}
// either Static metadata
export const metadata = {
title: '...',
}
// or Dynamic metadata
export async function generateMetadata({ params }) {
return {
title: '...',
}
}
很高兴知道:
¥Good to know:
仅服务器组件支持
metadata
对象和generateMetadata
函数导出。¥The
metadata
object andgenerateMetadata
function exports are only supported in Server Components.你不能从同一线路段同时导出
metadata
对象和generateMetadata
功能。¥You cannot export both the
metadata
object andgenerateMetadata
function from the same route segment.在初始加载时,流式被阻止,直到
generateMetadata
完全解析,包括来自loading.js
的任何内容。¥On the initial load, streaming is blocked until
generateMetadata
has fully resolved, including any content fromloading.js
.
metadata
对象
¥The metadata
object
要定义静态元数据,请从 layout.js
或 page.js
文件导出 Metadata
对象。
¥To define static metadata, export a Metadata
object from a layout.js
or page.js
file.
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: '...',
description: '...',
}
export default function Page() {}
export const metadata = {
title: '...',
description: '...',
}
export default function Page() {}
有关受支持选项的完整列表,请参阅 元数据字段。
¥See the Metadata Fields for a complete list of supported options.
generateMetadata
功能
¥generateMetadata
function
动态元数据依赖于动态信息,例如当前路由参数、外部数据或父段中的 metadata
,可以通过导出返回 Metadata
对象 的 generateMetadata
函数来设置。
¥Dynamic metadata depends on dynamic information, such as the current route parameters, external data, or metadata
in parent segments, can be set by exporting a generateMetadata
function that returns a Metadata
object.
import type { Metadata, ResolvingMetadata } from 'next'
type Props = {
params: Promise<{ id: string }>
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}
export async function generateMetadata(
{ params, searchParams }: Props,
parent: ResolvingMetadata
): Promise<Metadata> {
// read route params
const id = (await params).id
// fetch data
const product = await fetch(`https://.../${id}`).then((res) => res.json())
// optionally access and extend (rather than replace) parent metadata
const previousImages = (await parent).openGraph?.images || []
return {
title: product.title,
openGraph: {
images: ['/some-specific-page-image.jpg', ...previousImages],
},
}
}
export default function Page({ params, searchParams }: Props) {}
export async function generateMetadata({ params, searchParams }, parent) {
// read route params
const id = (await params).id
// fetch data
const product = await fetch(`https://.../${id}`).then((res) => res.json())
// optionally access and extend (rather than replace) parent metadata
const previousImages = (await parent).openGraph?.images || []
return {
title: product.title,
openGraph: {
images: ['/some-specific-page-image.jpg', ...previousImages],
},
}
}
export default function Page({ params, searchParams }) {}
参数
¥Parameters
generateMetadata
函数接受以下参数:
¥generateMetadata
function accepts the following parameters:
-
props
- 包含当前路由参数的对象:¥
props
- An object containing the parameters of the current route:-
params
- 包含从根段到段generateMetadata
的 动态路由参数 对象的对象被调用。示例:¥
params
- An object containing the dynamic route parameters object from the root segment down to the segmentgenerateMetadata
is called from. Examples:路由 URL params
app/shop/[slug]/page.js
/shop/1
{ slug: '1' }
app/shop/[tag]/[item]/page.js
/shop/1/2
{ tag: '1', item: '2' }
app/shop/[...slug]/page.js
/shop/1/2
{ slug: ['1', '2'] }
-
searchParams
- 包含当前 URL 的 搜索参数 的对象。示例:¥
searchParams
- An object containing the current URL's search params. Examples:URL searchParams
/shop?a=1
{ a: '1' }
/shop?a=1&b=2
{ a: '1', b: '2' }
/shop?a=1&a=2
{ a: ['1', '2'] }
-
-
parent
- 来自父路由段的已解析元数据的 promise。¥
parent
- A promise of the resolved metadata from parent route segments.
返回
¥Returns
generateMetadata
应返回包含一个或多个元数据字段的 Metadata
对象。
¥generateMetadata
should return a Metadata
object containing one or more metadata fields.
很高兴知道:
¥Good to know:
如果元数据不依赖于运行时信息,则应使用静态
metadata
对象 而不是generateMetadata
来定义它。¥If metadata doesn't depend on runtime information, it should be defined using the static
metadata
object rather thangenerateMetadata
.对于跨
generateMetadata
、generateStaticParams
、布局、页面和服务器组件的相同数据,fetch
请求自动为 memoized。如果fetch
不可用,则响应 可以使用cache
。¥
fetch
requests are automatically memoized for the same data acrossgenerateMetadata
,generateStaticParams
, Layouts, Pages, and Server Components. Reactcache
can be used iffetch
is unavailable.
searchParams
仅适用于page.js
航段。¥
searchParams
are only available inpage.js
segments.
redirect()
和notFound()
Next.js 方法也可以在generateMetadata
内部使用。¥The
redirect()
andnotFound()
Next.js methods can also be used insidegenerateMetadata
.
元数据字段
¥Metadata Fields
title
title
属性用于设置文档的标题。它可以定义为简单的 string 或可选的 模板对象。
¥The title
attribute is used to set the title of the document. It can be defined as a simple string or an optional template object.
字符串
¥String
export const metadata = {
title: 'Next.js',
}
<title>Next.js</title>
模板对象
¥Template object
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: {
template: '...',
default: '...',
absolute: '...',
},
}
export const metadata = {
title: {
default: '...',
template: '...',
absolute: '...',
},
}
默认
¥Default
title.default
可用于为未定义 title
的子路由段提供后备标题。
¥title.default
can be used to provide a fallback title to child route segments that don't define a title
.
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: {
default: 'Acme',
},
}
import type { Metadata } from 'next'
export const metadata: Metadata = {}
// Output: <title>Acme</title>
模板
¥Template
title.template
可用于向子路由段中定义的 titles
添加前缀或后缀。
¥title.template
can be used to add a prefix or a suffix to titles
defined in child route segments.
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: {
template: '%s | Acme',
default: 'Acme', // a default is required when creating a template
},
}
export const metadata = {
title: {
template: '%s | Acme',
default: 'Acme', // a default is required when creating a template
},
}
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'About',
}
// Output: <title>About | Acme</title>
export const metadata = {
title: 'About',
}
// Output: <title>About | Acme</title>
很高兴知道:
¥Good to know:
title.template
适用于子路由段,而不是其定义的段。这意味着:¥
title.template
applies to child route segments and not the segment it's defined in. This means:
添加
title.template
时需要title.default
。¥
title.default
is required when you add atitle.template
.
layout.js
中定义的title.template
不适用于同一航段的page.js
中定义的title
。¥
title.template
defined inlayout.js
will not apply to atitle
defined in apage.js
of the same route segment.
page.js
中定义的title.template
无效,因为页面始终是终止段(它没有任何子路由段)。¥
title.template
defined inpage.js
has no effect because a page is always the terminating segment (it doesn't have any children route segments).如果路由未定义
title
或title.default
,则title.template
无效。¥
title.template
has no effect if a route has not defined atitle
ortitle.default
.
绝对
¥Absolute
title.absolute
可用于提供忽略父段中设置的 title.template
的标题。
¥title.absolute
can be used to provide a title that ignores title.template
set in parent segments.
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: {
template: '%s | Acme',
},
}
export const metadata = {
title: {
template: '%s | Acme',
},
}
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: {
absolute: 'About',
},
}
// Output: <title>About</title>
export const metadata = {
title: {
absolute: 'About',
},
}
// Output: <title>About</title>
很高兴知道:
¥Good to know:
layout.js
title
(字符串)和title.default
定义子段的默认标题(不定义自己的title
)。它将从最近的父段(如果存在)增加title.template
。¥
title
(string) andtitle.default
define the default title for child segments (that do not define their owntitle
). It will augmenttitle.template
from the closest parent segment if it exists.
title.absolute
定义子段的默认标题。它忽略父段中的title.template
。¥
title.absolute
defines the default title for child segments. It ignorestitle.template
from parent segments.
title.template
为子段定义了新的标题模板。¥
title.template
defines a new title template for child segments.
page.js
如果页面没有定义自己的标题,则将使用最接近的父级解析标题。
¥If a page does not define its own title the closest parents resolved title will be used.
title
(字符串)定义路由标题。它将从最近的父段(如果存在)增加title.template
。¥
title
(string) defines the routes title. It will augmenttitle.template
from the closest parent segment if it exists.
title.absolute
定义路由标题。它忽略父段中的title.template
。¥
title.absolute
defines the route title. It ignorestitle.template
from parent segments.
title.template
在page.js
中没有任何作用,因为页面始终是路由的终止段。¥
title.template
has no effect inpage.js
because a page is always the terminating segment of a route.
description
export const metadata = {
description: 'The React Framework for the Web',
}
<meta name="description" content="The React Framework for the Web" />
基本字段
¥Basic Fields
export const metadata = {
generator: 'Next.js',
applicationName: 'Next.js',
referrer: 'origin-when-cross-origin',
keywords: ['Next.js', 'React', 'JavaScript'],
authors: [{ name: 'Seb' }, { name: 'Josh', url: 'https://next.nodejs.cn' }],
creator: 'Jiachi Liu',
publisher: 'Sebastian Markbåge',
formatDetection: {
email: false,
address: false,
telephone: false,
},
}
<meta name="application-name" content="Next.js" />
<meta name="author" content="Seb" />
<link rel="author" href="https://next.nodejs.cn" />
<meta name="author" content="Josh" />
<meta name="generator" content="Next.js" />
<meta name="keywords" content="Next.js,React,JavaScript" />
<meta name="referrer" content="origin-when-cross-origin" />
<meta name="color-scheme" content="dark" />
<meta name="creator" content="Jiachi Liu" />
<meta name="publisher" content="Sebastian Markbåge" />
<meta name="format-detection" content="telephone=no, address=no, email=no" />
metadataBase
metadataBase
是一个方便的选项,用于为需要完全限定 URL 的 metadata
字段设置基本 URL 前缀。
¥metadataBase
is a convenience option to set a base URL prefix for metadata
fields that require a fully qualified URL.
-
metadataBase
允许当前路由段及下面定义的基于 URL 的metadata
字段使用相对路径,而不是其他需要的绝对 URL。¥
metadataBase
allows URL-basedmetadata
fields defined in the current route segment and below to use a relative path instead of an otherwise required absolute URL. -
该字段的相对路径将与
metadataBase
组成一个完全限定的 URL。¥The field's relative path will be composed with
metadataBase
to form a fully qualified URL. -
如果未配置,
metadataBase
将自动填充为 默认值。¥If not configured,
metadataBase
is automatically populated with a default value.
export const metadata = {
metadataBase: new URL('https://acme.com'),
alternates: {
canonical: '/',
languages: {
'en-US': '/en-US',
'de-DE': '/de-DE',
},
},
openGraph: {
images: '/og-image.png',
},
}
<link rel="canonical" href="https://acme.com" />
<link rel="alternate" hreflang="en-US" href="https://acme.com/en-US" />
<link rel="alternate" hreflang="de-DE" href="https://acme.com/de-DE" />
<meta property="og:image" content="https://acme.com/og-image.png" />
很高兴知道:
¥Good to know:
metadataBase
通常在根app/layout.js
中设置,以应用于所有路由中基于 URL 的metadata
字段。¥
metadataBase
is typically set in rootapp/layout.js
to apply to URL-basedmetadata
fields across all routes.所有需要绝对 URL 的基于 URL 的
metadata
字段都可以使用metadataBase
选项进行配置。¥All URL-based
metadata
fields that require absolute URLs can be configured with ametadataBase
option.
metadataBase
可以包含子域,例如https://app.acme.com
或基本路径,例如https://acme.com/start/from/here
¥
metadataBase
can contain a subdomain e.g.https://app.acme.com
or base path e.g.https://acme.com/start/from/here
如果
metadata
字段提供绝对 URL,则metadataBase
将被忽略。¥If a
metadata
field provides an absolute URL,metadataBase
will be ignored.在基于 URL 的
metadata
字段中使用相对路径而不配置metadataBase
将导致构建错误。¥Using a relative path in a URL-based
metadata
field without configuring ametadataBase
will cause a build error.Next.js 会将
metadataBase
(例如https://acme.com/
)和相对字段(例如/path
)之间的重复斜杠标准化为单斜杠(例如https://acme.com/path
)¥Next.js will normalize duplicate slashes between
metadataBase
(e.g.https://acme.com/
) and a relative field (e.g./path
) to a single slash (e.g.https://acme.com/path
)
默认值
¥Default value
如果未配置,metadataBase
具有默认值。
¥If not configured, metadataBase
has a default value.
在 Vercel 上:
¥On Vercel:
对于生产部署,将使用
VERCEL_PROJECT_PRODUCTION_URL
。¥For production deployments,
VERCEL_PROJECT_PRODUCTION_URL
will be used.对于预览部署,
VERCEL_BRANCH_URL
将优先,如果不存在则回退到VERCEL_URL
。¥For preview deployments,
VERCEL_BRANCH_URL
will take priority, and fallback toVERCEL_URL
if it's not present.如果存在这些值,它们将用作
metadataBase
的默认值,否则将回退到http://localhost:${process.env.PORT || 3000}
。这允许 Open Graph 图片在本地构建和 Vercel 预览和生产部署中工作。覆盖默认值时,我们建议使用环境变量来计算 URL。这允许为本地开发、暂存和生产环境配置 URL。¥If these values are present they will be used as the default value of
metadataBase
, otherwise it falls back tohttp://localhost:${process.env.PORT || 3000}
. This allows Open Graph images to work on both local build and Vercel preview and production deployments. When overriding the default, we recommend using environment variables to compute the URL. This allows configuring a URL for local development, staging, and production environments.有关这些环境变量的更多详细信息,请参阅 系统环境变量 文档。
¥See more details about these environment variables in the System Environment Variables docs.
网址组成
¥URL Composition
URL 组合比默认目录遍历语义更有利于开发者的意图。
¥URL composition favors developer intent over default directory traversal semantics.
-
metadataBase
和metadata
字段之间的尾部斜杠已标准化。¥Trailing slashes between
metadataBase
andmetadata
fields are normalized. -
metadata
字段中的 "absolute" 路径(通常会替换整个 URL 路径)被视为 "relative" 路径(从metadataBase
末尾开始)。¥An "absolute" path in a
metadata
field (that typically would replace the whole URL path) is treated as a "relative" path (starting from the end ofmetadataBase
).
例如,给定以下 metadataBase
:
¥For example, given the following metadataBase
:
import type { Metadata } from 'next'
export const metadata: Metadata = {
metadataBase: new URL('https://acme.com'),
}
export const metadata = {
metadataBase: new URL('https://acme.com'),
}
任何继承上述 metadataBase
并设置自己值的 metadata
字段都将按如下方式解析:
¥Any metadata
fields that inherit the above metadataBase
and set their own value will be resolved as follows:
metadata 字段 | 已解析的网址 |
---|---|
/ | https://acme.com |
./ | https://acme.com |
payments | https://acme.com/payments |
/payments | https://acme.com/payments |
./payments | https://acme.com/payments |
../payments | https://acme.com/payments |
https://beta.acme.com/payments | https://beta.acme.com/payments |
openGraph
export const metadata = {
openGraph: {
title: 'Next.js',
description: 'The React Framework for the Web',
url: 'https://next.nodejs.cn',
siteName: 'Next.js',
images: [
{
url: 'https://next.nodejs.cn/og.png', // Must be an absolute URL
width: 800,
height: 600,
},
{
url: 'https://next.nodejs.cn/og-alt.png', // Must be an absolute URL
width: 1800,
height: 1600,
alt: 'My custom alt',
},
],
videos: [
{
url: 'https://next.nodejs.cn/video.mp4', // Must be an absolute URL
width: 800,
height: 600,
},
],
audio: [
{
url: 'https://next.nodejs.cn/audio.mp3', // Must be an absolute URL
},
],
locale: 'en_US',
type: 'website',
},
}
<meta property="og:title" content="Next.js" />
<meta property="og:description" content="The React Framework for the Web" />
<meta property="og:url" content="https://next.nodejs.cn/" />
<meta property="og:site_name" content="Next.js" />
<meta property="og:locale" content="en_US" />
<meta property="og:image" content="https://next.nodejs.cn/og.png" />
<meta property="og:image:width" content="800" />
<meta property="og:image:height" content="600" />
<meta property="og:image" content="https://next.nodejs.cn/og-alt.png" />
<meta property="og:image:width" content="1800" />
<meta property="og:image:height" content="1600" />
<meta property="og:image:alt" content="My custom alt" />
<meta property="og:video" content="https://next.nodejs.cn/video.mp4" />
<meta property="og:video:width" content="800" />
<meta property="og:video:height" content="600" />
<meta property="og:audio" content="https://next.nodejs.cn/audio.mp3" />
<meta property="og:type" content="website" />
export const metadata = {
openGraph: {
title: 'Next.js',
description: 'The React Framework for the Web',
type: 'article',
publishedTime: '2023-01-01T00:00:00.000Z',
authors: ['Seb', 'Josh'],
},
}
<meta property="og:title" content="Next.js" />
<meta property="og:description" content="The React Framework for the Web" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2023-01-01T00:00:00.000Z" />
<meta property="article:author" content="Seb" />
<meta property="article:author" content="Josh" />
很高兴知道:
¥Good to know:
对于 Open Graph 图片使用 基于文件的元数据 API 可能更方便。基于文件的 API 将自动为你生成正确的元数据,而不必将配置导出与实际文件同步。
¥It may be more convenient to use the file-based Metadata API for Open Graph images. Rather than having to sync the config export with actual files, the file-based API will automatically generate the correct metadata for you.
robots
import type { Metadata } from 'next'
export const metadata: Metadata = {
robots: {
index: false,
follow: true,
nocache: true,
googleBot: {
index: true,
follow: false,
noimageindex: true,
'max-video-preview': -1,
'max-image-preview': 'large',
'max-snippet': -1,
},
},
}
<meta name="robots" content="noindex, follow, nocache" />
<meta
name="googlebot"
content="index, nofollow, noimageindex, max-video-preview:-1, max-image-preview:large, max-snippet:-1"
/>
icons
很高兴知道:我们建议尽可能使用 基于文件的元数据 API 作为图标。基于文件的 API 将自动为你生成正确的元数据,而不必将配置导出与实际文件同步。
¥Good to know: We recommend using the file-based Metadata API for icons where possible. Rather than having to sync the config export with actual files, the file-based API will automatically generate the correct metadata for you.
export const metadata = {
icons: {
icon: '/icon.png',
shortcut: '/shortcut-icon.png',
apple: '/apple-icon.png',
other: {
rel: 'apple-touch-icon-precomposed',
url: '/apple-touch-icon-precomposed.png',
},
},
}
<link rel="shortcut icon" href="/shortcut-icon.png" />
<link rel="icon" href="/icon.png" />
<link rel="apple-touch-icon" href="/apple-icon.png" />
<link
rel="apple-touch-icon-precomposed"
href="/apple-touch-icon-precomposed.png"
/>
export const metadata = {
icons: {
icon: [
{ url: '/icon.png' },
new URL('/icon.png', 'https://example.com'),
{ url: '/icon-dark.png', media: '(prefers-color-scheme: dark)' },
],
shortcut: ['/shortcut-icon.png'],
apple: [
{ url: '/apple-icon.png' },
{ url: '/apple-icon-x3.png', sizes: '180x180', type: 'image/png' },
],
other: [
{
rel: 'apple-touch-icon-precomposed',
url: '/apple-touch-icon-precomposed.png',
},
],
},
}
<link rel="shortcut icon" href="/shortcut-icon.png" />
<link rel="icon" href="/icon.png" />
<link rel="icon" href="https://example.com/icon.png" />
<link rel="icon" href="/icon-dark.png" media="(prefers-color-scheme: dark)" />
<link rel="apple-touch-icon" href="/apple-icon.png" />
<link
rel="apple-touch-icon-precomposed"
href="/apple-touch-icon-precomposed.png"
/>
<link
rel="apple-touch-icon"
href="/apple-icon-x3.png"
sizes="180x180"
type="image/png"
/>
很高兴知道:Microsoft Edge 的 Chromium 版本不再支持
msapplication-*
元标记,因此不再需要。¥Good to know: The
msapplication-*
meta tags are no longer supported in Chromium builds of Microsoft Edge, and thus no longer needed.
themeColor
已弃用:从 Next.js 14 开始,
metadata
中的themeColor
选项已被弃用。请改用viewport
配置。¥Deprecated: The
themeColor
option inmetadata
is deprecated as of Next.js 14. Please use theviewport
configuration instead.
manifest
Web 应用清单,如 Web 应用清单规范.1 中所定义。
¥A web application manifest, as defined in the Web Application Manifest specification.
export const metadata = {
manifest: 'https://next.nodejs.cn/manifest.json',
}
<link rel="manifest" href="https://next.nodejs.cn/manifest.json" />
twitter
Twitter 规范(令人惊讶地)不仅仅用于 X(以前称为 Twitter)。
¥The Twitter specification is (surprisingly) used for more than just X (formerly known as Twitter).
了解有关 Twitter 卡标记参考 的更多信息。
¥Learn more about the Twitter Card markup reference.
export const metadata = {
twitter: {
card: 'summary_large_image',
title: 'Next.js',
description: 'The React Framework for the Web',
siteId: '1467726470533754880',
creator: '@nextjs',
creatorId: '1467726470533754880',
images: ['https://next.nodejs.cn/og.png'], // Must be an absolute URL
},
}
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site:id" content="1467726470533754880" />
<meta name="twitter:creator" content="@nextjs" />
<meta name="twitter:creator:id" content="1467726470533754880" />
<meta name="twitter:title" content="Next.js" />
<meta name="twitter:description" content="The React Framework for the Web" />
<meta name="twitter:image" content="https://next.nodejs.cn/og.png" />
export const metadata = {
twitter: {
card: 'app',
title: 'Next.js',
description: 'The React Framework for the Web',
siteId: '1467726470533754880',
creator: '@nextjs',
creatorId: '1467726470533754880',
images: {
url: 'https://next.nodejs.cn/og.png',
alt: 'Next.js Logo',
},
app: {
name: 'twitter_app',
id: {
iphone: 'twitter_app://iphone',
ipad: 'twitter_app://ipad',
googleplay: 'twitter_app://googleplay',
},
url: {
iphone: 'https://iphone_url',
ipad: 'https://ipad_url',
},
},
},
}
<meta name="twitter:site:id" content="1467726470533754880" />
<meta name="twitter:creator" content="@nextjs" />
<meta name="twitter:creator:id" content="1467726470533754880" />
<meta name="twitter:title" content="Next.js" />
<meta name="twitter:description" content="The React Framework for the Web" />
<meta name="twitter:card" content="app" />
<meta name="twitter:image" content="https://next.nodejs.cn/og.png" />
<meta name="twitter:image:alt" content="Next.js Logo" />
<meta name="twitter:app:name:iphone" content="twitter_app" />
<meta name="twitter:app:id:iphone" content="twitter_app://iphone" />
<meta name="twitter:app:id:ipad" content="twitter_app://ipad" />
<meta name="twitter:app:id:googleplay" content="twitter_app://googleplay" />
<meta name="twitter:app:url:iphone" content="https://iphone_url" />
<meta name="twitter:app:url:ipad" content="https://ipad_url" />
<meta name="twitter:app:name:ipad" content="twitter_app" />
<meta name="twitter:app:name:googleplay" content="twitter_app" />
viewport
已弃用:从 Next.js 14 开始,
metadata
中的viewport
选项已被弃用。请改用viewport
配置。¥Deprecated: The
viewport
option inmetadata
is deprecated as of Next.js 14. Please use theviewport
configuration instead.
verification
export const metadata = {
verification: {
google: 'google',
yandex: 'yandex',
yahoo: 'yahoo',
other: {
me: ['my-email', 'my-link'],
},
},
}
<meta name="google-site-verification" content="google" />
<meta name="y_key" content="yahoo" />
<meta name="yandex-verification" content="yandex" />
<meta name="me" content="my-email" />
<meta name="me" content="my-link" />
appleWebApp
export const metadata = {
itunes: {
appId: 'myAppStoreID',
appArgument: 'myAppArgument',
},
appleWebApp: {
title: 'Apple Web App',
statusBarStyle: 'black-translucent',
startupImage: [
'/assets/startup/apple-touch-startup-image-768x1004.png',
{
url: '/assets/startup/apple-touch-startup-image-1536x2008.png',
media: '(device-width: 768px) and (device-height: 1024px)',
},
],
},
}
<meta
name="apple-itunes-app"
content="app-id=myAppStoreID, app-argument=myAppArgument"
/>
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-title" content="Apple Web App" />
<link
href="/assets/startup/apple-touch-startup-image-768x1004.png"
rel="apple-touch-startup-image"
/>
<link
href="/assets/startup/apple-touch-startup-image-1536x2008.png"
media="(device-width: 768px) and (device-height: 1024px)"
rel="apple-touch-startup-image"
/>
<meta
name="apple-mobile-web-app-status-bar-style"
content="black-translucent"
/>
alternates
export const metadata = {
alternates: {
canonical: 'https://next.nodejs.cn',
languages: {
'en-US': 'https://next.nodejs.cn/en-US',
'de-DE': 'https://next.nodejs.cn/de-DE',
},
media: {
'only screen and (max-width: 600px)': 'https://next.nodejs.cn/mobile',
},
types: {
'application/rss+xml': 'https://next.nodejs.cn/rss',
},
},
}
<link rel="canonical" href="https://next.nodejs.cn" />
<link rel="alternate" hreflang="en-US" href="https://next.nodejs.cn/en-US" />
<link rel="alternate" hreflang="de-DE" href="https://next.nodejs.cn/de-DE" />
<link
rel="alternate"
media="only screen and (max-width: 600px)"
href="https://next.nodejs.cn/mobile"
/>
<link
rel="alternate"
type="application/rss+xml"
href="https://next.nodejs.cn/rss"
/>
appLinks
export const metadata = {
appLinks: {
ios: {
url: 'https://next.nodejs.cn/ios',
app_store_id: 'app_store_id',
},
android: {
package: 'com.example.android/package',
app_name: 'app_name_android',
},
web: {
url: 'https://next.nodejs.cn/web',
should_fallback: true,
},
},
}
<meta property="al:ios:url" content="https://next.nodejs.cn/ios" />
<meta property="al:ios:app_store_id" content="app_store_id" />
<meta property="al:android:package" content="com.example.android/package" />
<meta property="al:android:app_name" content="app_name_android" />
<meta property="al:web:url" content="https://next.nodejs.cn/web" />
<meta property="al:web:should_fallback" content="true" />
archives
描述记录、文档或其他具有历史意义的材料的集合 (source)。
¥Describes a collection of records, documents, or other materials of historical interest (source).
export const metadata = {
archives: ['https://next.nodejs.cn/13'],
}
<link rel="archives" href="https://next.nodejs.cn/13" />
assets
export const metadata = {
assets: ['https://next.nodejs.cn/assets'],
}
<link rel="assets" href="https://next.nodejs.cn/assets" />
bookmarks
export const metadata = {
bookmarks: ['https://next.nodejs.cn/13'],
}
<link rel="bookmarks" href="https://next.nodejs.cn/13" />
category
export const metadata = {
category: 'technology',
}
<meta name="category" content="technology" />
facebook
你可以将 Facebook 应用或 Facebook 账户连接到你的网页以获取某些 Facebook 社交插件 Facebook 文档
¥You can connect a Facebook app or Facebook account to you webpage for certain Facebook Social Plugins Facebook Documentation
很高兴知道:你可以指定 appId 或 admins,但不能同时指定两者。
¥Good to know: You can specify either appId or admins, but not both.
export const metadata = {
facebook: {
appId: '12345678',
},
}
<meta property="fb:app_id" content="12345678" />
export const metadata = {
facebook: {
admins: '12345678',
},
}
<meta property="fb:admins" content="12345678" />
如果你想生成多个 fb:admins 元标记,你可以使用数组值。
¥If you want to generate multiple fb:admins meta tags you can use array value.
export const metadata = {
facebook: {
admins: ['12345678', '87654321'],
},
}
<meta property="fb:admins" content="12345678" />
<meta property="fb:admins" content="87654321" />
other
应使用内置支持涵盖所有元数据选项。但是,可能有特定于你的站点的自定义元数据标签,或者刚刚发布的全新元数据标签。你可以使用 other
选项来渲染任何自定义元数据标签。
¥All metadata options should be covered using the built-in support. However, there may be custom metadata tags specific to your site, or brand new metadata tags just released. You can use the other
option to render any custom metadata tag.
export const metadata = {
other: {
custom: 'meta',
},
}
<meta name="custom" content="meta" />
如果你想生成多个相同的关键元标记,你可以使用数组值。
¥If you want to generate multiple same key meta tags you can use array value.
export const metadata = {
other: {
custom: ['meta1', 'meta2'],
},
}
<meta name="custom" content="meta1" /> <meta name="custom" content="meta2" />
不支持的元数据
¥Unsupported Metadata
以下元数据类型当前没有内置支持。但是,它们仍然可以在布局或页面本身中渲染。
¥The following metadata types do not currently have built-in support. However, they can still be rendered in the layout or page itself.
元数据 | 推荐 |
---|---|
<meta http-equiv="..."> | 通过 redirect() 、中间件、安全标头 使用适当的 HTTP 标头 |
<base> | 在布局或页面本身中渲染标签。 |
<noscript> | 在布局或页面本身中渲染标签。 |
<style> | 了解有关 Next.js 中的样式 的更多信息。 |
<script> | 了解有关 使用脚本 的更多信息。 |
<link rel="stylesheet" /> | import 样式表直接在布局或页面本身中。 |
<link rel="preload /> | 使用 ReactDOM 预加载方法 |
<link rel="preconnect" /> | 使用 ReactDOM 预连接方法 |
<link rel="dns-prefetch" /> | 使用 ReactDOM 预取 DNS 方法 |
资源提示
¥Resource hints
<link>
元素有许多 rel
关键字,可用于提示浏览器可能需要外部资源。浏览器使用此信息根据关键字应用预加载优化。
¥The <link>
element has a number of rel
keywords that can be used to hint to the browser that an external resource is likely to be needed. The browser uses this information to apply preloading optimizations depending on the keyword.
虽然元数据 API 不直接支持这些提示,但你可以使用 new ReactDOM
方法 将它们安全地插入到文档的 <head>
中。
¥While the Metadata API doesn't directly support these hints, you can use new ReactDOM
methods to safely insert them into the <head>
of the document.
'use client'
import ReactDOM from 'react-dom'
export function PreloadResources() {
ReactDOM.preload('...', { as: '...' })
ReactDOM.preconnect('...', { crossOrigin: '...' })
ReactDOM.prefetchDNS('...')
return '...'
}
'use client'
import ReactDOM from 'react-dom'
export function PreloadResources() {
ReactDOM.preload('...', { as: '...' })
ReactDOM.preconnect('...', { crossOrigin: '...' })
ReactDOM.prefetchDNS('...')
return '...'
}
<link rel="preload">
在页面渲染(浏览器)生命周期的早期开始加载资源。MDN 文档。
¥Start loading a resource early in the page rendering (browser) lifecycle. MDN Docs.
ReactDOM.preload(href: string, options: { as: string })
<link rel="preload" href="..." as="..." />
<link rel="preconnect">
抢先发起与源点的连接。MDN 文档。
¥Preemptively initiate a connection to an origin. MDN Docs.
ReactDOM.preconnect(href: string, options?: { crossOrigin?: string })
<link rel="preconnect" href="..." crossorigin />
<link rel="dns-prefetch">
在请求资源之前尝试解析域名。MDN 文档。
¥Attempt to resolve a domain name before resources get requested. MDN Docs.
ReactDOM.prefetchDNS(href: string)
<link rel="dns-prefetch" href="..." />
很高兴知道:
¥Good to know:
这些方法目前仅在客户端组件中受支持,这些组件在初始页面加载时仍然在服务器端渲染。
¥These methods are currently only supported in Client Components, which are still Server Side Rendered on initial page load.
Next.js 内置功能(例如
next/font
、next/image
和next/script
)会自动处理相关资源提示。¥Next.js in-built features such as
next/font
,next/image
andnext/script
automatically handle relevant resource hints.
类型
¥Types
你可以使用 Metadata
类型向元数据添加类型安全性。如果你在 IDE 中使用 内置 TypeScript 插件,则无需手动添加类型,但如果需要,你仍然可以显式添加它。
¥You can add type safety to your metadata by using the Metadata
type. If you are using the built-in TypeScript plugin in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want.
metadata
对象
¥metadata
object
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Next.js',
}
generateMetadata
功能
¥generateMetadata
function
常规功能
¥Regular function
import type { Metadata } from 'next'
export function generateMetadata(): Metadata {
return {
title: 'Next.js',
}
}
异步函数
¥Async function
import type { Metadata } from 'next'
export async function generateMetadata(): Promise<Metadata> {
return {
title: 'Next.js',
}
}
带分段属性
¥With segment props
import type { Metadata } from 'next'
type Props = {
params: Promise<{ id: string }>
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}
export function generateMetadata({ params, searchParams }: Props): Metadata {
return {
title: 'Next.js',
}
}
export default function Page({ params, searchParams }: Props) {}
带有父元数据
¥With parent metadata
import type { Metadata, ResolvingMetadata } from 'next'
export async function generateMetadata(
{ params, searchParams }: Props,
parent: ResolvingMetadata
): Promise<Metadata> {
return {
title: 'Next.js',
}
}
JavaScript 项目
¥JavaScript Projects
对于 JavaScript 项目,你可以使用 JSDoc 添加类型安全。
¥For JavaScript projects, you can use JSDoc to add type safety.
/** @type {import("next").Metadata} */
export const metadata = {
title: 'Next.js',
}
版本历史
¥Version History
版本 | 变化 |
---|---|
v13.2.0 | viewport 、themeColor 和 colorScheme 已弃用,取而代之的是 viewport 配置。 |
v13.2.0 | 推出 metadata 和 generateMetadata 。 |