Next.js - 元数据

网页的元数据存储重要信息,如网页标题、描述、标题卡图像等。适当的元数据对于更好的搜索引擎结果至关重要。在本章中,我们将解释 Next.js 中的元数据对象,如何定义静态和动态元数据,如何使用 CSS 生成元数据图像。

Next.js 中的元数据对象

在 Next.js 中,元数据对象是 App Router 的一部分,用于定义每个路由的元数据。使用元数据对象,我们可以定义标题、描述和其他 SEO 组件,即使是动态生成的路由。以下是元数据对象的语法。

export const metadata = {
    title: "网页标题",
    description: "网页描述"
}

Title 属性

title 属性用于设置文档的标题。它可以定义为一个简单的字符串或一个可选的模板对象。

import type { Metadata } from 'next'
 
export const metadata: Metadata = {
  title: {
    default: '...', 
    template: '...', 
    absolute: '...', 
  },
}
  • default :此默认标题值,定义子路由的后备标题
  • template :用于为子路由中定义的标题添加前缀或后缀
  • absolute :用于提供忽略父路由中设置的 title.template 的标题。

声明静态元数据

静态元数据是指不依赖于外部源数据的元数据。此静态元数据对于所有用户都保持不变,并且在编写应用程序时定义。

在应用路由器中,您可以通过从"layout.tsx"或静态"page.tsx"文件导出元数据对象来定义静态元数据。layout.tsx 中定义的元数据可供布局中的所有组件访问。page.tsx 中定义的元数据特定于该组件,它可以覆盖布局页面的元数据。

布局组件元数据示例

在下面的代码中,我们使用元数据对象为布局组件定义元数据。我们定义的标题将显示在浏览器选项卡的顶部。

// app/layout.tsx file

import { ReactNode } from 'react';
import type { Metadata } from 'next'
 
export const metadata: Metadata = {
  title: 'Next JS Tutorial',
  description: 'We provide simple and easy to learn tutorial on Next JS',
}

interface RootLayoutProps {
  children: ReactNode;
}

export default function RootLayout({ children }: RootLayoutProps) {
  return (
    <html lang="en">
      <body>
        <header>
            <h1>Header Element</h1>
        </header>
        <main>{children}</main>
      </body>
    </html>
  );
}

输出

以下是上述代码的输出。标题元数据以红色矩形突出显示。

next.js-static-metadata-layout

任何组件的元数据示例

如上所述,我们可以在任何组件内覆盖布局页面的元数据。在下面的示例中,我们为"关于"页面定义了新的标题和描述。

// app/about/page.tsx file

import type { Metadata } from 'next';
 
export const metadata: Metadata = {
  title: 'Next JS About Page',
  description: 'We provide simple and easy to learn tutorial on Next JS',
}

export default function About() {
    return (
        <div>
            <h1>About Us</h1>
            <h2>Welcome to the Next JS About page!</h2>
            <h4>This page is same for all users</h4>
        </div>
    );
}    

输出

这是上述两段代码的组合输出。您可以看到,布局页面中定义的元数据是默认元数据,当我们打开"关于"页面时,它会被"关于"页面的元数据覆盖。

静态元数据示例

声明动态元数据

动态元数据依赖于动态信息,例如当前路由参数、外部数据或父段中的元数据。可以通过导出返回元数据对象的"generateMetadata()"函数来设置它。在阅读示例之前,先了解动态路由的工作原理。

基于路由的动态标题示例

在下面的示例中,我们将根据用户选择的页面为组件生成动态标题。

// app/products/[id]/page.tsx

import { Metadata } from "next";

type Props ={
    params: {
        id: string;
    };
}
// 动态元数据函数
export const generateMetadata = ({ params }: Props): Metadata => {
    return {
        title: `Product ${params.id} - My Store`,
    };
}

export default function ProductPage({params }: Props) {

    return (
        <div>
            <h1>Product {params.id}</h1>
            <p>This is the product page for item {params.id}</p>
        </div>
    );
}

输出

在输出中,您可以看到页面根据我们选择的路线而变化。

动态元数据

元数据图像生成

元数据图像用于创建社交媒体图像,例如 Open Graph 图像、Twitter 卡片等。当我们的网页链接在 Whatsapp、Twitter 等中共享时,将显示此图像。

简单 Hello World 图像示例

以下示例使用 ImageResponse 构造函数通过 JSX 和 CSS 生成动态图像。我们将在同一网页中显示生成的图像,以便您可以在输出中看到它。

// app/api/og/route.js

import { ImageResponse } from 'next/og';

export async function GET() {
  return new ImageResponse(
    (
      <div
        style={{
          fontSize: 50,
          background: 'grey',
          color: '#f0f0f0',
          width: '100%',
          height: '100%',
          display: 'flex',
          textAlign: 'center',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        Hello world!
      </div>
    ),
    {
      width: 300,
      height: 100,
    }
  );
}

// app/contacts/page.js

export default function Page() {
    return (
      <div>
        <h1>Contacts Page</h1>
        <img src="/api/og" alt="Generated Image" />
      </div>
    );
  }

输出

在下面的输出中,您可以看到生成的带有"Hello World"消息的图像。

元数据图像