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

如何在esbuild中成功构建monaco-editor?构建后运行报错求助

用esbuild构建monaco-editor Worker时的运行时错误解决方法

问题重现

在其他平台使用相同配置可正常运行,但用esbuild构建monaco-editor的editor.worker.js后,项目运行时出现控制台错误。

构建配置

esbuild.build({
  entryPoints: ['node_modules/monaco-editor/esm/vs/editor/editor.worker.js'],
  outfile: outfile,
  bundle: true,
  format: 'iife'
}).then(() => {
  console.log('Build complete, save at ' + outfile)
})

项目引用代码

self.MonacoEnvironment = {
  getWorker() {
    return new Worker('/assets/editor.worker.js')
  },
}
import(
  'monaco-editor/esm/vs/basic-languages/typescript/typescript.contribution'
).then(() => {
  import('monaco-editor').then(({ editor }) => {
    editor.create(container.current, {
      language: 'typescript',
    })
  })
})

错误信息

错误发生在这段代码执行时:

if (!initialized) {
  initialize(null);
}

错误截图

问题原因

esbuild使用iife格式打包Worker是核心问题:iife会将代码包裹在自执行函数中,破坏了monaco-editor Worker依赖的全局上下文环境,导致内部的initialize函数无法正确访问所需的变量和模块导出,进而抛出错误。而其他平台可能默认使用ES模块格式打包,或者对Worker的上下文处理更符合monaco的预期。

解决方案

将esbuild的打包格式改为esm,因为Worker原生支持ES模块,这样打包后的代码能保持monaco所需的上下文环境:

修改后的构建配置:

esbuild.build({
  entryPoints: ['node_modules/monaco-editor/esm/vs/editor/editor.worker.js'],
  outfile: outfile,
  bundle: true,
  format: 'esm' // 替换原有的iife格式
}).then(() => {
  console.log('Build complete, save at ' + outfile)
})

补充说明

  • 现代浏览器均支持ES模块格式的Worker,无需额外兼容处理;
  • 如果需要兼容旧版本浏览器,可以在配置中添加target: 'es2018'来指定目标环境,确保打包后的代码兼容性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:25:18