You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js+Contentlayer项目:next-sitemap未收录博客页面求助

解决方案

1. 调整next-sitemap.config.js注入动态路径

next-sitemap默认仅识别静态页面,需要手动导入Contentlayer生成的博客数据,将动态路径添加到站点地图中:

const siteMetadata = require("./utils/siteMetaData");
const { allBlogs } = require("./.contentlayer/generated");

module.exports = {
  siteUrl: siteMetadata.siteUrl,
  generateRobotsTxt: true,
  additionalPaths: async (config) => {
    const paths = [];

    // 注入所有博客文章路径
    allBlogs.forEach((blog) => {
      paths.push({
        loc: `${config.siteUrl}${blog.url}`,
        lastmod: new Date(blog.updatedAt || blog.publishedAt).toISOString(),
        changefreq: "weekly",
        priority: 0.8,
      });
    });

    // 手动添加其他核心静态页面(如首页、关于页等)
    const corePages = ["/", "/about", "/archive"];
    corePages.forEach((page) => {
      paths.push({
        loc: `${config.siteUrl}${page}`,
        lastmod: new Date().toISOString(),
        changefreq: "monthly",
        priority: 0.9,
      });
    });

    return paths;
  },
};

2. 修正构建脚本顺序

在package.json中调整构建流程,确保Contentlayer先完成内容生成,再执行站点地图构建:

{
  "scripts": {
    "build": "next build",
    "postbuild": "contentlayer build && next-sitemap"
  }
}

3. 验证结果

执行npm run build后,查看生成的sitemap-0.xml,此时应该包含所有博客文章URL及手动添加的核心页面。

核心说明

  • next-sitemap无法自动识别Contentlayer生成的动态路由,因为这类路径是构建时动态生成的,不属于Next.js默认扫描的静态页面范畴。
  • 通过additionalPaths可以直接利用Contentlayer输出的allBlogs数据,批量注入博客路径,同时补充核心静态页面的收录。

内容的提问来源于stack exchange,提问作者sonu kkc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 08:39:52