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

Gatsby从两类Markdown文件生成页面时出现错误,请求排查原因

解决Gatsby从Markdown生成页面时的"Exported queries are only executed for Page components"错误

你的联合查询在GraphiQL里能正常获取数据,但执行gatsby develop时触发的这个错误,本质上是gatsby-node.js里的页面创建逻辑有bug导致流程中断,Gatsby给出的提示有点误导性。我帮你找出了两个核心问题:

1. 缺少path模块的导入

你的代码里用了path.resolve来指定模板文件路径,但没有在文件顶部导入path模块,这会直接抛出ReferenceError: path is not defined,打断页面创建流程。

2. Posts循环中引用了未定义的变量

在posts的forEach循环里,你写了:

const previous = index === nodes.length - 1 ? null : posts[index + 1]

这里的nodes是循环的当前节点参数(forEach的第一个参数是当前元素,第二个是索引),并不是外层的posts数组,应该改成posts.length,否则会抛出ReferenceError: nodes is not defined,导致整个createPage逻辑失败。

修复后的完整gatsby-node.js代码

const path = require('path') // 新增path模块导入

exports.createPage = ({ graphql, actions }) => { 
  const { createPage } = actions 
  const blogTemplate = path.resolve("./src/templates/blog-details.js") 
  const projectTemplate = path.resolve("./src/templates/project-details.js") 

  return graphql(` 
    query { 
      projects: allMarkdownRemark( 
        filter: { fileAbsolutePath: { regex: "/projects/" } } 
        sort: { fields: [frontmatter___date], order: DESC } 
      ) { 
        nodes { 
          frontmatter { slug title } 
          fileAbsolutePath 
        } 
      } 
      posts: allMarkdownRemark( 
        filter: { fileAbsolutePath: { regex: "/posts/" } } 
        sort: { fields: [frontmatter___date], order: DESC } 
      ) { 
        nodes { 
          frontmatter { slug title } 
          fileAbsolutePath 
        } 
      } 
    } 
  `).then(result => { 
    if (result.errors) { 
      Promise.reject(result.errors) 
    } 

    const projects = result.data.projects.nodes 
    const posts = result.data.posts.nodes 

    // 创建项目页面
    projects.forEach((node) => { 
      createPage({ 
        path: "/projects/" + node.frontmatter.slug, 
        component: projectTemplate, 
        context: { slug: node.frontmatter.slug }, 
      }) 
    }) 

    // 创建博客页面
    posts.forEach((node, index) => { 
      const next = index === 0 ? null : posts[index - 1] 
      // 修复nodes为posts
      const previous = index === posts.length - 1 ? null : posts[index + 1] 
      createPage({ 
        path: "/blog/" + node.frontmatter.slug, 
        component: blogTemplate, 
        context: { 
          slug: node.frontmatter.slug, 
          previous, 
          next, 
        }, 
      }) 
    }) 
  }) 
}

验证步骤

  1. 把修复后的代码替换到你的gatsby-node.js文件中
  2. 执行gatsby clean清除旧缓存(这一步很重要,避免缓存残留导致的问题)
  3. 重新启动gatsby develop,应该就能正常生成页面了

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 03:42:43