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

Gatsby搭建Markdown博客时本地图片无法正常加载问题求助

问题排查与解决步骤

1 基础路径与配置校验

  • 确认你的markdown文件存放路径:如果markdown文件放在src/posts/目录下,../images/new-provider.jpg的相对路径是正确的;如果路径层级不对,先修正frontmatter中image字段的相对路径。
  • 确认gatsby-config.js中已经配置了markdown/MDX文件所在目录的gatsby-source-filesystem规则,示例配置如下:
{
  resolve: 'gatsby-source-filesystem',
  options: {
    name: 'posts',
    path: `${__dirname}/src/posts/`, // 替换为你实际存放博客md的目录
  },
}
  • 执行gatsby clean清除本地缓存后重启开发服务,排除缓存干扰。

2 修正GraphQL查询逻辑

你当前查询返回的image字段只是字符串类型的相对路径,没有经过sharp插件处理,无法直接用于图片组件渲染,需要修改查询语句获取处理后的图片节点:

export const query = graphql`
  query PostsByID($slug: String!) {
    mdx(slug: { eq: $slug }) {
      body
      frontmatter {
        title
        authors
        date
        featured
        image {
          # 用于GatsbyImage组件的处理后数据
          childImageSharp {
            gatsbyImageData(layout: CONSTRAINED, width: 1200)
          }
          # 如果你要使用原生img标签,查询publicURL字段
          publicURL
        }
        tags
      }
    }
  }
`;

你可以先打开http://localhost:8000/___graphql调试查询,如果image字段下没有childImageSharp字段,说明路径配置错误,回到第一步校验路径。

3 修正图片渲染代码

方案1:使用官方推荐的GatsbyImage组件(支持懒加载、自适应格式)

首先从依赖中导入对应组件:

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

渲染时调用辅助方法获取图片数据:

const imageData = getImage(mdx.frontmatter.image)
// 渲染组件
<GatsbyImage image={imageData} alt={title} key={title} />

注意:旧版gatsby-image的Img组件已经废弃,不要继续使用

方案2:使用原生img标签

直接用查询到的publicURL作为src属性即可:

<img alt={title} src={mdx.frontmatter.image.publicURL} />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:36:02