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

如何在electron-vue中集成monaco editor?集成时出现Cannot find module 'monaco-editor'错误的求助

解决Electron-Vue中Monaco Editor ESM集成的"Cannot find module 'monaco-editor'"错误

这个问题的核心原因很明确:你的Webpack配置把monaco-editor当成了外部依赖,跳过了打包流程,导致Electron运行时找不到这个模块。

具体问题分析

看你renderer的Webpack配置里的externals部分:

externals: [
    ...Object.keys(dependencies || {}).filter(d => !whiteListedModules.includes(d))
]

这段代码会把package.json的dependencies里所有不在白名单的包,都排除在Webpack的打包处理之外。而monaco-editor正好在你的dependencies里,且没被加入白名单,所以Webpack不会解析它的模块,运行时Electron就会抛出找不到模块的错误。

分步解决方案

1. 将monaco-editor加入Webpack白名单

修改你的whiteListedModules数组,把monaco-editor加进去,让Webpack正常处理这个模块:

// 找到你的whiteListedModules定义,修改成这样
const whiteListedModules = ['vue', 'vue-router', 'vuex', 'monaco-editor']

或者直接在externals的过滤逻辑里排除它:

externals: [
    ...Object.keys(dependencies || {}).filter(d => !whiteListedModules.includes(d) && d !== 'monaco-editor')
]

2. 正确配置monaco-editor-webpack-plugin

你已经安装了这个插件,但还没在Webpack里启用它,它能帮你自动处理Monaco的Worker文件和模块解析,不需要手动在entry里添加各个Worker入口。

  • 首先在renderer的Webpack配置文件顶部引入插件:
    const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')
    
  • 然后在plugins数组里添加插件配置:
    plugins: [
        // 保留你已有的其他插件...
        new MonacoWebpackPlugin({
            // 只打包你需要的语言,减少体积
            languages: ['html', 'json', 'css', 'javascript'],
            // 指定Worker文件的输出路径,和你的项目结构匹配
            filename: 'static/[name].worker.js'
        })
    ]
    
  • 做完这一步,你可以删掉entry里手动添加的editor.worker、json.worker等入口,插件会自动处理这些。

3. 调整MonacoEnvironment的Worker路径

因为用了Webpack插件,Worker文件的输出路径会变成static/[name].worker.js,所以修改你的getWorkerUrl逻辑:

self.MonacoEnvironment = {
    getWorkerUrl: function (moduleId, label) {
        // 适配插件生成的Worker文件名
        let workerName = label;
        if (label === 'javascript' || label === 'typescript') {
            workerName = 'ts';
        }
        return `./static/${workerName}.worker.js`;
    }
};

4. 验证版本兼容性

你的Electron版本是2.0.4,Monaco Editor 0.26.1和对应的webpack插件版本是兼容的,如果后续还有奇怪问题,可以考虑把Electron升级到更稳定的新版本(比如13.x或更高),不过当前组合应该能正常运行。

按照这些步骤调整后,重新启动项目,Cannot find module 'monaco-editor'的错误应该就会消失了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 06:56:57