使用 MDX 在 Gatsby 博客中添加 featuresImage
Posted
技术标签:
【中文标题】使用 MDX 在 Gatsby 博客中添加 featuresImage【英文标题】:Add featuredImage in a Gatsby blog with MDX 【发布时间】:2021-01-31 15:25:13 【问题描述】:我正在尝试在我的 Gatsby 博客上添加特色图片,但无法成功。我尝试了在这里和那里找到的几件事,但我一直收到此错误消息:Field "featuredImage" must not have a selection since type "String" has no subfields.
这是我的博客结构:
src
|- images
|- house.jpeg
| - pages
|- actualites
|- house.mdx
我的house.mdx
有以下主要内容:
---
title: House
path: /house
date: 2019-01-29
featuredImage: ../../images/house.jpeg
---
我的gatsby-plugin
看起来像这样:
plugins: [
`gatsby-plugin-resolve-src`,
resolve: `gatsby-source-filesystem`,
options:
path: `$__dirname/src/images`,
,
,
resolve: `gatsby-source-filesystem`,
options:
path: `$__dirname/src/pages`,
,
,
resolve: `gatsby-transformer-remark`,
options:
plugins: [
resolve: `gatsby-remark-images`,
options:
maxWidth: 800,
,
,
],
,
,
resolve: `gatsby-plugin-mdx`,
options:
gatsbyRemarkPlugins: [
resolve: `gatsby-remark-images`,
options:
maxWidth: 1200,
,
,
],
,
,
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
],
我不知道我做错了什么... http://localhost:8000/___graphql 显示了我的featuredImage
,但没有显示图像的子字段,所以我猜它不明白我的领域是图像。
你能帮我指出我缺少什么吗?
谢谢你????
【问题讨论】:
您是否尝试过添加name
? gatsbyjs.com/plugins/gatsby-source-filesystem
是的,我试过了。但它并没有改变任何东西,所以我删除了它。
【参考方案1】:
问题通常来自多个来源:
当字符串路径(在您的情况下为图像)的命名存在差异时。例如,如果您正在寻找:../../images/house.jpeg
,但图像被放置或命名为house.jpg
(不是jpeg
)。作为相对路径,我认为问题来自那里。尝试将其更改为./path/to/image.jpg
检查拼写
检查插件顺序
使用 GraphQL Playground (localhost:8000/___graphql
) 通过在此处创建特定查询来检查图像的正确路径。
参考资料/有用资源:
https://github.com/gatsbyjs/gatsby/issues/13322 https://github.com/gatsbyjs/gatsby/issues/4123 https://dev.to/stephencweiss/error-field-image-must-not-have-a-selection-since-type-string-has-no-subfields-3a76 https://spectrum.chat/gatsby-js/general/this-error-field-img-must-not-have-a-selection-since-type-string~05669aa2-8045-4875-a82b-c52e53df791e【讨论】:
感谢您的回答。在发布之前,我在其他帖子中看到通常文件的命名或路径是问题的原因。所以我检查了多次,名称和路径都正确。在 GraphQL 游乐场中,我无法将我的字段作为图像进行查询。插件顺序是什么意思?有没有发病率? 你试过改变相对路径吗?../..
到 ./
或类似名称。插件的顺序也很重要,在您的情况下,在 sn-p 中是正确的(我也假设在您的项目中),但需要检查。在 Playground 中,您可以创建另一个查询来获取图像的路径,这可能对检查路径很有用。
是的,我尝试更改路径,并将 sharp
插件移到列表顶部,但我仍然遇到同样的问题。我真的不知道该怎么办,我被卡住了:/【参考方案2】:
我终于可以让它工作了。
问题是我在我的 graphQL 中请求 allSitePage
而不是 allMdx
。现在我可以将路径视为图像并请求其所有子字段。
【讨论】:
以上是关于使用 MDX 在 Gatsby 博客中添加 featuresImage的主要内容,如果未能解决你的问题,请参考以下文章
MDX 中的 Gatsby 静态图像(gatsby-plugin-image)
无法从 gatsby-plugin-mdx 导入 MDXRenderer