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

迁移gatsby-starter-texblog至Gatsby v4遇MDX解析错误求助

升级Gatsby-plugin-mdx v3到v4后MDX文件被当作JS解析的错误修复

问题概述

基于gatsby-starter-texblog模板升级Gatsby至v4版本,已按照gatsby-plugin-mdx v3→v4迁移指南完成以下操作:

  • 移除gatsby-config.js中的defaultLayouts选项,迁移gatsby-remark及remark插件至正确位置
  • 修改gatsby-node.js,添加?__contentFilePath=参数
  • 更新postpage.tsx接收children,替换MDX渲染器为{children}

但运行gatsby develop时,MDX文件的Frontmatter(---开头部分)被当作JavaScript语法解析,触发以下错误:

ERROR #gatsby-plugin-mdx_10001  PLUGIN

Failed to compile the file
"/home/faberf/Documents/fynns-blog/content/posts/hello-world.mdx". Original
error message:

Expected usable value, not `undefined`


 ERROR 

Module build failed (from ./node_modules/gatsby/dist/utils/babel-loader.js):
SyntaxError: /home/faberf/Documents/fynns-blog/content/posts/hello-world.mdx:
Invalid left-hand side in prefix operation. (1:2)

> 1 | ---
    |   ^
  2 | title: Hello World
  3 | date: "2023-03-17"
  4 | description: "In this blog, I will be sharing insights into my various 
computer science projects. 
    at instantiate (/home/faberf/Documents/fynns-blog/node_modules/@babel/parser
/src/parse-error/credentials.ts:62:21)

错误原因分析

  1. 依赖版本不兼容:@mdx-js/react v2.3.0要求React v17+,但当前依赖中React版本为v16,版本不匹配导致MDX解析逻辑失效
  2. 插件配置冲突:同时安装了gatsby-transformer-remark和gatsby-plugin-mdx,可能导致文件解析优先级混乱,MDX文件被错误用remark解析
  3. MDX插件配置缺失:gatsby-plugin-mdx未正确指定文件扩展名或MDX解析选项,导致插件未识别.mdx文件格式

修复方案

1. 对齐核心依赖版本

更新React至兼容版本:

npm install react@^17.0.0 react-dom@^17.0.0

2. 修正gatsby-config.js的MDX插件配置

确保gatsby-plugin-mdx正确识别文件扩展名,并配置对应的remark/rehype插件(替代原gatsby-remark系列插件),同时移除冲突的gatsby-transformer-remark:

// gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-mdx`,
      options: {
        extensions: [`.mdx`, `.md`],
        mdxOptions: {
          remarkPlugins: [require(`remark-math`)],
          rehypePlugins: [require(`rehype-katex`)],
        },
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `posts`,
        path: `${__dirname}/content/posts/`,
      },
    },
    // 保留其他必要插件,移除gatsby-transformer-remark
  ],
};

3. 验证gatsby-node.js的页面生成逻辑

确保查询allMdx而非allMarkdownRemark,并正确传递__contentFilePath:

// gatsby-node.js
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;
  const result = await graphql(`
    query {
      allMdx {
        nodes {
          id
          fields {
            slug
          }
          internal {
            contentFilePath
          }
        }
      }
    }
  `);

  result.data.allMdx.nodes.forEach(node => {
    createPage({
      path: `/posts/${node.fields.slug}`,
      component: require.resolve(`./src/templates/postpage.tsx`),
      context: {
        id: node.id,
        __contentFilePath: node.internal.contentFilePath,
      },
    });
  });
};

4. 确认postpage.tsx的渲染逻辑

确保组件正确接收children并配合MDXProvider渲染:

// src/templates/postpage.tsx
import React from 'react';
import { MDXProvider } from '@mdx-js/react';
import { graphql } from 'gatsby';

export const query = graphql`
  query($id: String!) {
    mdx(id: { eq: $id }) {
      frontmatter {
        title
        date
        description
      }
    }
  }
`;

const PostPage = ({ data, children }) => {
  const post = data.mdx;
  return (
    <MDXProvider>
      <div className="post-container">
        <h1>{post.frontmatter.title}</h1>
        <p>{post.frontmatter.date}</p>
        <p>{post.frontmatter.description}</p>
        <div className="post-content">{children}</div>
      </div>
    </MDXProvider>
  );
};

export default PostPage;

5. 清理缓存并重装依赖

执行以下命令确保环境干净:

rm -rf node_modules package-lock.json
npm install
gatsby clean
gatsby develop

补充说明

  • 移除gatsby-remark-katex依赖,改用remark-math+rehype-katex组合适配MDX解析逻辑
  • 检查所有MDX文件的Frontmatter格式,确保无语法错误(如引号未闭合、逗号缺失)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:07:16