You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

在Electron+React(Electron Forge)中配置Monaco Editor遇模块缺失错误求助

解决Electron Forge + React中Monaco Editor的加载问题

Hey there, I totally get the frustration of switching over from mobile/desktop dev to web tech and hitting weird module errors—especially with Monaco's finicky AMD loading setup. Let's get this sorted out step by step:

问题根源

Monaco Editor uses a non-standard AMD module system that doesn't play nice with Electron Forge's default Webpack configuration out of the box. Unlike Ace Editor (which uses standard ES/CommonJS modules), Monaco needs extra Webpack handling to resolve its modules and static assets (like language packs and styles).

具体修复步骤

1. 安装必要依赖

First, make sure you have both react-monaco-editor and the core monaco-editor installed, plus the Webpack plugin that handles Monaco's special needs:

yarn add react-monaco-editor monaco-editor
yarn add --dev monaco-editor-webpack-plugin

2. 修改Webpack配置

Electron Forge uses separate Webpack configs for the main process and renderer process. You'll need to update the renderer config to include the Monaco plugin:

  • If you already have a webpack.renderer.config.js file in your project root, modify it like this:
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = {
  // 保留你现有的配置项(比如entry、module规则等)
  plugins: [
    // 添加这个插件来处理Monaco的模块加载
    new MonacoWebpackPlugin({
      // 只指定你需要的语言,减少打包体积
      languages: ['javascript']
    })
  ]
};
  • If you don't have a separate renderer config, update your forge.config.js to point to a custom renderer config:
module.exports = {
  packagerConfig: {},
  rebuildConfig: {},
  makers: [],
  plugins: [
    {
      name: '@electron-forge/plugin-webpack',
      config: {
        mainConfig: './webpack.main.config.js',
        renderer: {
          config: './webpack.renderer.config.js', // 指向你的新渲染进程配置文件
          entryPoints: [
            {
              html: './src/index.html',
              js: './src/renderer.js',
              name: 'main_window'
            }
          ]
        }
      }
    }
  ]
};

3. 调整你的Editor组件

Update your src/app.jsx to include basic dimensions (so you can actually see the editor) and a default value:

import React from 'react';
import MonacoEditor from 'react-monaco-editor';

export default class App extends React.Component {
  render() {
    const defaultCode = '// Write your JavaScript code here!';
    return (
      <MonacoEditor
        width="800px"
        height="600px"
        language="javascript"
        value={defaultCode}
      />
    );
  }
}

4. 重启项目

Finally, stop your running dev server and restart it:

npm start

为什么Ace Editor能正常工作但Monaco不行?

Ace使用标准的ES/CommonJS模块语法,完美适配Electron Forge默认的Webpack配置。而Monaco最初是为VS Code环境构建的,依赖AMD加载机制,必须通过Webpack插件转换才能让Electron识别。

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

火山引擎 最新活动