【问题标题】:Unable to add images to mdx file in Gatsby无法将图像添加到 Gatsby 中的 mdx 文件
【发布时间】:2021-04-29 00:49:07
【问题描述】:

我正在尝试通过执行以下操作将图像导入 mdx 文件:![alt](image.jpg)。我的 mdx 文件和图像都存储在目录 src、posts、post-1 中。但是,图像不显示。我尝试了许多文件路径,但都没有成功。

我能够显示图像的唯一方法是使用 src 例如![alt](/static/47d93fd9bdeaaf54a7b60d14c66abe5d/48e00/icon.jpg)

以下是我的 gatsby.config 的一部分

plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `pages`,
        path: `${__dirname}/src/pages/`,
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "images",
        path: `${__dirname}/src/images/`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `posts`,
        path: `${__dirname}/src/posts/`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `post-featured`,
        path: `${__dirname}/src/post-featured/`,
      },
    },
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
    {
      resolve: "gatsby-plugin-mdx",
      options: {
        root: __dirname,
        extensions: [".md", ".mdx"],
        gatsbyRemarkPlugins: [
          {
            resolve: "gatsby-remark-images",
            options: {
              maxWidth: 800,
              quality: 70,
            },
          },
        ],
      },
    },

【问题讨论】:

    标签: gatsby gatsby-image gatsby-remark-image


    【解决方案1】:

    我认为您需要将图像引用为以./ 开头的相对路径,例如![alt](./image.jpg)

    在文档中不是特别清楚,但在https://www.gatsbyjs.org/packages/gatsby-remark-images/#usage-in-markdown中提到

    【讨论】:

      【解决方案2】:

      我通过在我的博客文章 mdx frontmatter 例如添加一个图像数组来解决这个问题。 images: [formby-golf-club.jpg, myFirstTweet.PNG].

      然后在我的帖子模板中,我通过 graphQL 获取数组中图像的 publicURL,并将它们传递给 MDXRenderer,如下所示:<MDXRenderer images={data.mdx.frontmatter.images}>

      然后我可以像这样访问我的 mdx 文件中的图像数组:<img src={props.images[0].publicURL} style={{ width: "100%" }} />

      【讨论】:

        【解决方案3】:

        在阅读official how-to guide 并将gatsby-remark-image 添加为插件数组中的单个条目后,我遇到了同样的问题。仅将其保留在 gatsby-plugin-mdx 内部解决了我的问题。

        【讨论】:

          猜你喜欢
          • 2021-07-17
          • 2021-01-07
          • 1970-01-01
          • 2020-03-06
          • 2020-12-18
          • 2023-03-15
          • 2021-01-02
          • 2020-12-03
          • 2021-01-31
          相关资源
          最近更新 更多