MDX内部的Gatsby静态图像(Gatsby-plugin-Image)

最近我开始使用Gatsby,现在我正在尝试使用MDX,在我的MDX文件中,我可以通过GraphQL使用Gatsby Image,但我想使用Gatsby-Plugin-Image中的静态图像,我收到了如下错误:

Reaction_DevTools_Backend.js:2557未加载图像 https://images.unsplash.com/photo-1597305877032-0668b3c6413a?w=1300

当我尝试在.tsx中实现此图像时,它起作用了,所以我想知道这是否可能。

Gatsby-CONFIG

 "gatsby-remark-images",
    {
      resolve: "gatsby-plugin-mdx",
      options: {
        defaultLayouts: {
          default: require.resolve("./src/components/common/Layout.tsx")
        },
        gatsbyRemarkPlugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {},
          },
        ],
      }
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "images",
        path: `${__dirname}/src/images/`,
      },
      __key: "images",
    },

然后在test.mdx中,我尝试使用这样的静态图像:

<StaticImage
    src={'https://images.unsplash.com/photo-1597305877032-0668b3c6413a?w=1300'}
    alt={''}
    width={3840}
    height={1000}
    layout={'constrained'}
/>

mdx

不能在推荐答案文档中直接使用gatsby-plugin-image。This post on the Gatsby blog说明如何通过FrontMatter传递图像参考道具来间接使用它。

就我个人而言,我可以这样做:

此示例仅加载本地映像,请参阅博客文章了解如何引用远程映像,因为它比较复杂。

模板组件

import React from "react";
import { graphql } from "gatsby";
import { MDXRenderer } from "gatsby-plugin-mdx";
import Layout from "../components/layout";

const Game = ({ data }) => {
  const { mdx } = data;
  const { frontmatter, body } = mdx;
  return (
    <Layout title={frontmatter.title}>
      <span className="date">{frontmatter.date}</span>
      <MDXRenderer localImages={frontmatter.embeddedImagesLocal}>
        {body}
      </MDXRenderer>
    </Layout>
  );
};

export const pageQuery = graphql`
  query($slug: String!) {
    mdx(slug: { eq: $slug }) {
      slug
      body
      frontmatter {
        date(formatString: "MMMM DD, YYYY")
        title
        embeddedImagesLocal {
          childImageSharp {
            gatsbyImageData
          }
        }
      }
    }
  }
`;

export default Game;

MDX文档

---
title: Death Stranding
author: Hideo Kojima
date: 2021-05-06
template: game
embeddedImagesLocal:
  - '../images/20210513035720_1.jpg'
---

import { getImage, GatsbyImage } from 'gatsby-plugin-image';

A great game from Hideo Kojima.

<GatsbyImage alt='Sam in a destroyed mall' image={getImage(props.localImages[0])} />

相关文章