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

Gatsby如何通过GraphQL查询src/data子目录下的所有YAML文件

问题1:无法查询到allBooksYaml的原因

这不是插件bug,是配置不符合节点生成规则导致的。gatsby-transformer-yaml默认会根据单个YAML文件的文件名生成对应的查询节点,你当前看到的allQuote1Yaml、allQuote2Yaml就是默认规则的产物。

要生成统一的allBooksYaml查询节点,调整配置即可:

  1. 先在gatsby-config.js中为书籍引用目录单独配置gatsby-source-filesystem实例:
module.exports = {
  plugins: [
    // 其他已有插件
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `books`,
        path: `${__dirname}/src/data/books/`,
      },
    },
    {
      resolve: `gatsby-transformer-yaml`,
      options: {
        typeName: ({ node }) => node.sourceInstanceName === 'books' ? 'BooksYaml' : 'Yaml'
      }
    }
  ]
}
  1. 配置完成后重启Gatsby开发服务,GraphiQL中就会出现allBooksYaml查询入口,包含该目录下所有YAML文件的数据。

问题2:YAML数据与Markdown/页面的关联方案

推荐两种落地性强的方案:

  • 上下文传参过滤方案:在所有读书笔记Markdown文件的frontmatter中新增bookId字段,同时在每本书对应的YAML引用数据中也新增相同的bookId标识。用createPagesAPI生成笔记页面时,把bookId作为页面上下文传递,在booknote.tsx的GraphQL查询中按bookId过滤allBooksYaml即可获取对应书籍的引用内容,示例查询如下:
query BookNotePageQuery($bookId: String!) {
  markdownRemark(frontmatter: {bookId: {eq: $bookId}}) {
    html
    frontmatter {
      title
      publishDate
    }
  }
  allBooksYaml(filter: {bookId: {eq: $bookId}}) {
    nodes {
      quote
      chapter
    }
  }
}
  • 节点绑定方案:通过Gatsby的createSchemaCustomizationAPI直接在构建阶段建立Markdown节点和YAML节点的关联,无需在页面侧手动过滤。在gatsby-node.js中添加如下配置:
exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions
  createTypes(`
    type MarkdownRemark implements Node {
      relatedQuotes: [BooksYaml] @link(by: "bookId", from: "frontmatter.bookId")
    }
  `)
}

配置完成后,直接在Markdown节点的查询中就能获取关联的引用数据,查询逻辑更简洁。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:27:04