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

Gatsby多文章类型(博客/项目)build报错问题求助

Gatsby Build阶段内容路由错误问题排查与修复

核心问题根源

Gatsby在build时错误将博客文章生成到项目路径,本质是未对MDX内容做类型过滤:

  • 配置gatsby-source-filesystem时未给目录添加类型标记,导致GraphQL无法区分博客和项目内容
  • 页面模板的GraphQL查询未限制内容来源,两个模板会匹配所有MDX文件,生成重复页面,非对应路径的内容自然返回null

具体修复步骤

1. 完善文件源配置(gatsby-config.js)

给每个文件源添加name字段标记内容类型,让GraphQL能区分不同目录的内容:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `blog`, // 标记博客内容
        path: `${__dirname}/blog/`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `projects`, // 标记项目内容
        path: `${__dirname}/projects/`,
      },
    },
    // 保留其他已有插件配置
  ],
}

2. 修改页面模板的GraphQL查询

博客详情页(pages/blog/{mdx.frontmatter__slug}.js)

给查询添加sourceInstanceName过滤,只获取博客目录下的内容:

query($id: String!) {
  mdx(id: {eq: $id}, sourceInstanceName: {eq: "blog"}) {
    frontmatter {
      title
      slug
    }
    body
  }
}

项目详情页(pages/projects/{mdx.frontmatter__slug}.js)

同理,限制只查询项目目录下的内容:

query($id: String!) {
  mdx(id: {eq: $id}, sourceInstanceName: {eq: "projects"}) {
    frontmatter {
      title
      slug
    }
    body
  }
}

3. 优化列表页查询(可选)

为避免列表页展示交叉内容,博客和项目的列表页也需添加对应过滤,比如博客列表页(pages/blog/index.js)的查询:

query {
  allMdx(filter: {sourceInstanceName: {eq: "blog"}}) {
    nodes {
      frontmatter {
        title
        slug
      }
      id
    }
  }
}

验证修复流程

  1. 执行gatsby clean清除旧缓存
  2. 运行gatsby build,此时每个MDX文件只会生成对应路径的页面,不会出现数据为null的TypeError

内容的提问来源于stack exchange,提问作者Лео

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:48:22