You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gatsby中react-markdown渲染本地图片失败求助

解决Gatsby中react-markdown渲染本地图片失败的问题

问题原因

直接在markdown的img标签里写本地图片文件名,Gatsby构建时会将静态资源迁移到public/static目录下并生成哈希文件名,原相对路径无法匹配到构建后的资源位置,导致图片加载失败。

解决方案

方案一:通过GraphQL查询映射图片路径(适配react-markdown+rehypeRaw)

  1. 安装必要插件
    在项目根目录执行:

    npm install gatsby-source-filesystem gatsby-plugin-image gatsby-transformer-sharp gatsby-plugin-sharp
    
  2. 配置gatsby-config.js
    添加文件系统读取规则,指向你的文章目录:

    module.exports = {
      plugins: [
        {
          resolve: `gatsby-source-filesystem`,
          options: {
            name: `posts`,
            path: `${__dirname}/content/posts/`, // 替换为你的文章存放路径
          },
        },
        `gatsby-plugin-image`,
        `gatsby-transformer-sharp`,
        `gatsby-plugin-sharp`,
      ],
    }
    
  3. 自定义react-markdown的img组件
    在渲染markdown的页面组件中,通过GraphQL获取所有图片的构建后路径,替换原img标签的src:

    import { useStaticQuery, graphql } from "gatsby"
    import ReactMarkdown from "react-markdown"
    import rehypeRaw from "rehype-raw"
    
    const PostPage = ({ data }) => {
      // 查询所有本地图片
      const allImages = useStaticQuery(graphql`
        query {
          allFile(filter: { extension: { in: ["png", "jpg", "jpeg"] } }) {
            nodes {
              name
              publicURL
            }
          }
        }
      `)
    
      // 生成图片名称到构建后路径的映射表
      const imageMap = allImages.allFile.nodes.reduce((map, img) => {
        map[img.name] = img.publicURL
        return map
      }, {})
    
      return (
        <ReactMarkdown
          rehypePlugins={[rehypeRaw]}
          components={{
            // 自定义img组件替换路径
            img: ({ src, alt, className }) => {
              // 从映射表中获取正确路径,找不到则保留原路径(兼容网络图片)
              const imageUrl = imageMap[src.split('.')[0]] || src
              return <img src={imageUrl} alt={alt} className={className} />
            }
          }}
        >
          {data.post.content}
        </ReactMarkdown>
      )
    }
    
    // 查询当前文章的内容
    export const query = graphql`
      query($slug: String!) {
        post: file(relativePath: { eq: $slug }) {
          content
        }
      }
    `
    
    export default PostPage
    

方案二:使用MDX原生导入图片(推荐,支持图片优化)

如果项目使用MDX,可以直接在MDX文件中导入图片,无需依赖react-markdown的自定义组件:

  1. 安装gatsby-plugin-mdx

    npm install gatsby-plugin-mdx @mdx-js/react
    
  2. 配置gatsby-config.js
    在plugins数组中添加:

    {
      resolve: `gatsby-plugin-mdx`,
      options: {
        extensions: [`.mdx`, `.md`],
      },
    }
    
  3. 修改index.mdx内容
    直接导入本地图片并使用:

    import AppwizImage from './346fd5bb-f993-4497-9036-da99fe9e1d76.png'
    
    <figure class="figure text-center col-xs-12 col-sm-12 col-lg-12">
      <img src={AppwizImage} class="img-fluid" alt="Running appwiz.cpl">
      <figcaption class="figure-caption text-center fw-normal text-dark">Running appwiz.cpl.</figcaption>
    </figure>
    

方案三:使用static目录(不推荐,无图片优化)

将图片放到项目根目录的static/images文件夹下,直接使用绝对路径:

<figure class="figure text-center col-xs-12 col-sm-12 col-lg-12">
  <img src="/images/346fd5bb-f993-4497-9036-da99fe9e1d76.png" class="img-fluid" alt="Running appwiz.cpl">
  <figcaption class="figure-caption text-center fw-normal text-dark">Running appwiz.cpl.</figcaption>
</figure>

该方法无需额外配置,但Gatsby不会对图片进行压缩、响应式优化,仅适合临时场景。


内容的提问来源于stack exchange,提问作者Berkay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 10:35:17