【问题标题】:gatsby-plugin-image and GraphQL don't recognize my image frontmatter when .mdx is outside of /pages/ directory当 .mdx 位于 /pages/ 目录之外时,gatsby-plugin-image 和 GraphQL 无法识别我的图像 frontmatter
【发布时间】:2021-07-27 20:55:15
【问题描述】:

背景:

我正在使用页面布局模板以编程方式在/src/content/ 中创建带有 .mdx 文件的页面。一切正常,直到我需要从 .mdx 文件的 frontmatter 中获取图像,格式如下:

示例:/src/content/.../.../hello-world.mdx

---
title: foo
image: ../images/icon.png
---
hello world.

我在gatsby-config.js 中安装并引用了插件 gatsby-plugin-image、gatsby-plugin-sharp、gatsby-source-filesystem 和 gatsby-transformer-sharp。此外,我使用 gatsby-source-filesystem 的选项设置了我的 gatsby-config.js 文件,以在 /src/content 中查找 .mdx 文件。

问题:

Gatsby 声明 here “任何包含图像的 GraphQL 文件对象都将具有一个 childImageSharp 字段,您可以使用它来查询图像数据。”然而,这对我来说并没有发生:

它只是将 frontmatter 中的 image: 键视为字符串,而从不给它 childImageSharp 字段。试图通过写出字段来强制查询只会导致错误。

但是!!!

如果我将同一个 .mdx 文件放入 /src/pages 中,突然 gatsby-plugin-image 开始正常运行并给出 childImageSharp 字段:

为什么?

更新:将 .mdx 文件放入 /src/content/ 有效,childImageSharp 字段出现在 GraphQL 中,但 .mdx 文件放置在更深的位置(例如:src/content/recipes/guacamole/)不起作用。

【问题讨论】:

    标签: graphql gatsby yaml-front-matter


    【解决方案1】:

    回答:

    ../images/icon.png 不是 /src/content/recipes/guac/ 中的文件引用 /src/images/ 中的图像的有效路径。我的图像密钥在 .mdx frontmatter 中的正确路径应该相对于 .mdx 的位置(例如:image: ../../../images/icon.png)。

    我的路径是错误的。因此 GraphQL 没有将其识别为文件,也没有创建 childImageSharp 字段。

    【讨论】:

      猜你喜欢
      • 2020-12-03
      • 2021-07-17
      • 2021-12-31
      • 2020-02-28
      • 2020-02-03
      • 2021-09-16
      • 2022-01-15
      • 2020-05-10
      • 2020-03-09
      相关资源
      最近更新 更多