NNext.js 中文网 GitHub

generateSitemaps

了解如何使用 generateSitemaps 函数为应用程序创建多个站点地图。

你可以使用 generateSitemaps 函数为应用程序生成多个站点地图(sitemap)。

返回值#

generateSitemaps 返回一个包含 id 属性的对象数组。

URL#

生成的站点地图将位于 /.../sitemap/[id].xml。例如 /product/sitemap/1.xml。

示例#

例如,要使用 generateSitemaps 拆分站点地图,请返回一个包含站点地图 id 的对象数组。然后,使用该 id 生成各自的站点地图。

app/product/sitemap.ts
import type { MetadataRoute } from 'next'
import { BASE_URL } from '@/app/lib/constants'

export async function generateSitemaps() {
  // 获取商品总数并计算所需的站点地图数量
  return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]
}

export default async function sitemap(props: {
  id: Promise<string>
}): Promise<MetadataRoute.Sitemap> {
  const id = await props.id
  // Google 的限制是每个站点地图 50,000 个 URL
  const start = id * 50000
  const end = start + 50000
  const products = await getProducts(
    `SELECT id, date FROM products WHERE id BETWEEN ${start} AND ${end}`
  )
  return products.map((product) => ({
    url: `${BASE_URL}/product/${product.id}`,
    lastModified: product.date,
  }))
}
app/product/sitemap.js
import { BASE_URL } from '@/app/lib/constants'

export async function generateSitemaps() {
  // 获取商品总数并计算所需的站点地图数量
  return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]
}

export default async function sitemap(props) {
  const id = await props.id
  // Google 的限制是每个站点地图 50,000 个 URL
  const start = id * 50000
  const end = start + 50000
  const products = await getProducts(
    `SELECT id, date FROM products WHERE id BETWEEN ${start} AND ${end}`
  )
  return products.map((product) => ({
    url: `${BASE_URL}/product/${product.id}`,
    lastModified: product.date,
  }))
}

版本历史#

版本变更
v16.0.0现在,从 generateSitemaps 返回的 id 值会作为一个解析为 string 的 Promise 传递给 sitemap 函数。
v15.0.0generateSitemaps 现在会在开发和生产环境之间生成一致的 URL
v13.3.2引入 generateSitemaps。在开发环境中,你可以在 /.../sitemap.xml/[id] 查看生成的站点地图。例如 /product/sitemap.xml/1。
Next.js 中文网