pdo*_*zal 9 javascript typescript gatsby
最近我开始使用 Gatsby,现在我正在尝试使用 MDX,在我的 MDX 文件中,我可以通过 GraphQL 使用 Gatsby 图像,但我想使用 gatsby-plugin-image 中的静态图像,但出现错误像这样:
react_devtools_backend.js:2557 图像未加载 https://images.unsplash.com/photo-1597305877032-0668b3c6413a?w=1300
当我尝试在 .tsx 中实现此图像时,它可以工作,所以我想知道它是否可能。
gatsby 配置
"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",
},
Run Code Online (Sandbox Code Playgroud)
然后在 test.mdx 中我尝试使用静态图像,如下所示:
<StaticImage
src={'https://images.unsplash.com/photo-1597305877032-0668b3c6413a?w=1300'}
alt={''}
width={3840}
height={1000}
layout={'constrained'}
/>
Run Code Online (Sandbox Code Playgroud)
您不能gatsby-plugin-image直接在 MDX 文档中使用。Gatsby 博客上的这篇文章解释了如何通过 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;
Run Code Online (Sandbox Code Playgroud)
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])} />
Run Code Online (Sandbox Code Playgroud)