使用rsbuild集成monaco-editor时如何消除依赖提取警告?
在使用Rsbuild构建集成monaco-editor的项目时,不管有没有引入monaco-editor-webpack-plugin,构建过程都会弹出以下警告:
⚠ Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
╭─[319:16]
317 │ };
318 │ if (!isESM) {
319 │ require([${moduleId}], onModuleCallback, reject);
· ───────
320 │ }
321 │ else {
╰────
只要导入并使用monaco的任意功能(比如执行new monaco.Range())就会触发这个警告。已知该警告基本无害,但可以通过以下方法屏蔽:
复现步骤
- 创建简易Rsbuild项目:
npx create-rsbuild -d monaco-esm-issue -t vanilla - 进入项目目录:
cd monaco-esm-issue - 安装基础依赖:
npm install - 安装monaco-editor:
npm install monaco-editor - 修改
src/index.js为以下内容后执行npm run dev:
import * as monaco from 'monaco-editor'; new monaco.Range();
执行后终端就会出现上述警告。
解决方案
方法1:全局关闭动态require类警告
在项目的rsbuild.config.js中添加配置,关闭Rspack(Rsbuild底层)的exprContextCritical类型警告:
export default { tools: { rspack: { module: { exprContextCritical: false, }, }, }, };
此配置会屏蔽所有因动态require导致的同类警告,适合确认这类警告都无害的场景。
方法2:仅针对monaco-editor屏蔽警告
如果不想全局关闭,可精准针对monaco-editor的代码屏蔽:
export default { tools: { rspack: { module: { rules: [ { test: /monaco-editor\/.*\.js$/, parser: { exprContextCritical: false, }, }, ], }, }, }, };
方法3:使用monaco-editor的ESM版本
直接导入monaco-editor的ESM入口,从根源减少动态require的使用,可能直接消除警告:
// 替换原来的导入语句 import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'; new monaco.Range();
内容的提问来源于stack exchange,提问作者momesana

