You need to enable JavaScript to run this app. 使用@monaco-editor/react遇模块解析错误,寻求有效解决方法
优惠活动
大模型
产品
解决方案
定价
更多

使用@monaco-editor/react遇模块解析错误,寻求有效解决方法

解决@monaco-editor/react模块解析错误(Unexpected token)

错误详情

./node_modules/@monaco-editor/react/dist/index.mjs 124:62
Module parse failed: Unexpected token (124:62)
File was processed with these loaders:

  • ./node_modules/babel-loader/lib/index.js
    You may need an additional loader to handle the result of these loaders.

触发错误的代码片段:

return i.then(f => (c.current = f) && s(!1)).catch(f => f?.type !== "cancelation" && console.error("Monaco initialization: error:", f)), () => u.current ? I() : i.cancel();

解决步骤

  • 添加Babel可选链语法支持
    错误中的f?.type是ES2020可选链操作符,旧版Babel未默认支持。安装对应插件并配置:

    npm install @babel/plugin-proposal-optional-chaining --save-dev
    

    在babel.config.json或.babelrc中加入:

    {
      "plugins": ["@babel/plugin-proposal-optional-chaining"]
    }
    
  • 让babel-loader转译@monaco-editor/react
    默认babel-loader不会处理node_modules内的代码,需在webpack配置中把该包加入转译范围:

    module.exports = {
      module: {
        rules: [
          {
            test: /\.(js|mjs|jsx)$/,
            include: [
              path.resolve(__dirname, 'src'),
              path.resolve(__dirname, 'node_modules/@monaco-editor/react')
            ],
            use: 'babel-loader'
          }
        ]
      }
    }
    
  • 升级核心依赖版本
    老旧的webpack、babel-loader、@babel/core可能导致语法解析失败,执行升级命令:

    npm update webpack babel-loader @babel/core
    
  • 切换到CommonJS版本导入
    直接导入库的CommonJS版本,绕开ES模块解析问题:

    import { Editor } from '@monaco-editor/react/lib/index.js';
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:16:10