最近我开始使用Gatsby,现在我正在尝试使用MDX,在我的MDX文件中,我可以通过GraphQL使用Gatsby,但是我想使用中的静态图像,我收到了这样的错误:
react_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'}
/>发布于 2021-05-17 18:35:47
不能在MDX文档中直接使用gatsby-plugin-image。这篇文章发表在盖茨比博客上解释了如何通过前端传递图像参考道具间接地使用它。
就我个人而言,我可以这样做:
此示例仅加载本地图像,请参阅博客文章,以了解如何引用远程图像,因为它更复杂。
模板组件
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])} />发布于 2021-10-13 16:09:51
您可以将gatsby-remark-images插件与gatsby-plugin-mdx一起使用,它为您处理图像。
安装插件,然后在gatsby-config.js中更新gatsby-plugin-mdx如下所示:
{
resolve: 'gatsby-plugin-mdx',
options: {
gatsbyRemarkPlugins: [
{
resolve: `gatsby-remark-images`,
options: {
maxWidth: 900,
},
},
],
plugins: [`gatsby-remark-images`]
},
},然后,图像按照预期使用标记格式工作。
不幸的是,maxWidth是通过网站固定的,这对我来说并不理想。我使用的是@bonobolabs/gatsby-remark-images-custom-widths叉,它允许您使用HTML img标记在MDX文件中指定图像宽度:
<img src="./image.jpg" alt="My image" width="500px"/>我相信它只是‘宽度’,这是额外的属性,这给你。
https://stackoverflow.com/questions/67227977
复制相似问题