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

Gatsby中MDX远程图片创建File节点数组查询报错如何解决

问题根源

报错核心原因是@link指令依赖节点ID完成关联,但你在createNodeField时存入localFile字段的是完整File节点对象数组,Gatsby在执行关联查询时尝试将整个对象作为索引键序列化,直接触发序列化错误。

Gatsby的节点关联逻辑完全基于唯一ID实现,不支持直接存储完整节点对象做关联,你可以通过两步修改解决问题:


步骤1:修改onCreateNode存储逻辑

仅存储生成的File节点ID数组,不要存完整节点对象:

exports.onCreateNode = async ({
  node,
  actions,
  store,
  cache,
  createNodeId,
}) => {
  const { createNodeField, createNode } = actions;

  if (node.internal.type === "Mdx" && node.frontmatter.images) {
    const imageNodeIds = [];

    for (let image of node.frontmatter.images) {
      const fileNode = await createRemoteFileNode({
        url: image,
        parentNodeId: node.id,
        createNode,
        createNodeId,
        cache,
        store,
      });

      if (fileNode) {
        imageNodeIds.push(fileNode.id); // 仅存入节点ID
      }
    }

    createNodeField({ node, name: "localFile", value: imageNodeIds });
  }
};

步骤2:补全Schema类型定义

你当前的Fields类型没有声明localFile字段,补全后可以避免类型推断异常:

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions;

  createTypes(`
    type Mdx implements Node {
      frontmatter: Frontmatter
      fields: Fields
      images: [File] @link(from: "fields.localFile")
    }

    type Frontmatter {
      title: String
      images: [String]
    }

    type Fields {
      slug: String
      localFile: [ID] # 明确为ID数组类型,和存储的内容匹配
    }
  `);
};

验证生效

修改完成后执行gatsby clean清理旧缓存节点,重启开发服务后再执行你的查询,即可正常获取images字段下的所有File属性,包括childImageSharp相关处理字段,完全支持File节点数组的关联查询。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:54:01