generateSitemaps
了解如何使用 generateSitemaps 函数为你的应用创建多个 sitemap。
你可以使用 generateSitemaps 函数为你的应用生成多个 sitemap。
返回值
generateSitemaps 返回一个对象数组,其中的对象带有 id 属性。
URL
你生成的 sitemap 可通过 /.../sitemap/[id].xml 访问。例如,/product/sitemap/1.xml。
示例
例如,要使用 generateSitemaps 拆分 sitemap,可返回一个对象数组,其中包含 sitemap id。然后,使用 id 生成各个唯一的 sitemap。
TypeScript
app/product/sitemap.tsts
import type { MetadataRoute } from 'next'
import { BASE_URL } from '@/app/lib/constants'
export async function generateSitemaps() {
// Fetch the total number of products and calculate the number of sitemaps needed
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's limit is 50,000 URLs per sitemap
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,
}))
}
JavaScript
app/product/sitemap.jsjs
import { BASE_URL } from '@/app/lib/constants'
export async function generateSitemaps() {
// Fetch the total number of products and calculate the number of sitemaps needed
return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]
}
export default async function sitemap(props) {
const id = await props.id
// Google's limit is 50,000 URLs per sitemap
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 值现在会以 Promise 的形式传递给 sitemap 函数,该 Promise 解析为 string。 |
v15.0.0 |
generateSitemaps 现在在开发环境和生产环境中生成一致的 URL |
v13.3.2 |
引入 generateSitemaps。在开发环境中,你可以在 /.../sitemap.xml/[id] 上查看生成的 sitemap。例如,/product/sitemap.xml/1。 |
后续步骤
了解如何为你的 Next.js 应用创建 sitemap。
- sitemap.xml:sitemap.xml 文件的 API 参考。