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

如何在Gatsby的MDX中通过frontmatter生成Sharp优化图像?

我明白你的痛点——gatsby-remark-images确实只处理MDX正文里的图片,frontmatter里的图片路径只会保留原始值,不会自动经过Sharp优化。下面给你两种实用的解决方案,帮你搞定这个问题:

方案一:通过GraphQL查询获取处理后的Frontmatter图片

这是社区里最常用的解决方案,利用Gatsby的文件系统和Sharp转换器直接处理frontmatter中的图片:

  1. 确保依赖安装完整
    先确认你已经安装了这些必要的插件(如果没有的话):

    npm install gatsby-source-filesystem gatsby-transformer-sharp gatsby-plugin-sharp
    
  2. 更新gatsby-config.js配置
    添加gatsby-source-filesystem指向你的MDX和图片所在目录,同时启用Sharp相关插件:

    module.exports = {
      plugins: [
        // 保留你已有的page-creator配置
        { 
          resolve: "gatsby-plugin-page-creator", 
          options: { path: `${__dirname}/src/data/mdx` }, 
        },
        // 添加图片目录的文件系统源
        {
          resolve: 'gatsby-source-filesystem',
          options: {
            name: 'mdx-images',
            path: `${__dirname}/src/data/mdx`, // 图片和MDX同目录时用这个路径
          },
        },
        // 启用Sharp处理插件
        'gatsby-plugin-sharp',
        'gatsby-transformer-sharp',
        // 保留你已有的MDX配置
        {
          resolve: 'gatsby-plugin-mdx',
          options: {
            defaultLayouts: { 
              default: require.resolve("./src/templates/mdx.js") 
            },
            gatsbyRemarkPlugins: [
              {
                resolve: `gatsby-remark-images`,
                options: {
                  maxWidth: 992,
                  backgroundColor: 'transparent',
                  withWebp: true,
                },
              },
            ],
          },
        },
      ],
    }
    
  3. 修改MDX模板文件(mdx.js),添加GraphQL查询
    现在你可以通过GraphQL查询获取frontmatter中image的Sharp处理后的资源,替换掉原始路径:

    import { graphql } from 'gatsby';
    import { GatsbyImage, getImage } from 'gatsby-plugin-image'; // 新版推荐用这个
    import Layout from '../components/layout'; // 替换成你的Layout组件路径
    
    export default ({ children, data, pageContext }) => {
      const frontmatter = pageContext.frontmatter;
      const heroImage = getImage(data.mdx.frontmatter.image);
    
      return (
        <Layout>
          {/* 展示经过Sharp优化的图片 */}
          {heroImage && <GatsbyImage image={heroImage} alt={frontmatter.name} />}
          {children}
        </Layout>
      );
    };
    
    // GraphQL查询,获取frontmatter里的图片处理节点
    export const query = graphql`
      query($id: String!) {
        mdx(id: { eq: $id }) {
          frontmatter {
            image {
              childImageSharp {
                gatsbyImageData(width: 992, formats: [WEBP, AUTO])
              }
            }
            name
          }
        }
      }
    `;
    

    如果你还在使用旧版的gatsby-image,可以替换为Img组件和fluid查询,语法类似。

方案二:自定义MDX节点处理(进阶)

如果你希望frontmatter里的image自动转换为处理后的资源,不需要每次写查询,可以通过Gatsby的onCreateNode API来扩展MDX节点,把处理后的图片数据注入到pageContext里。不过这种方式相对复杂,方案一已经能满足大多数场景,推荐优先使用方案一。

额外注意事项

  • 确保frontmatter里的图片是相对路径,且和MDX文件在同一目录(或者你在gatsby-source-filesystem里配置了正确的图片目录)。
  • 如果图片放在独立目录(比如src/images),需要单独添加一个gatsby-source-filesystem指向该目录。
  • 修改配置后记得重启Gatsby开发服务器,确保文件节点被正确创建。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:28:01