React Node项目更新依赖后NPM Test报ERR_REQUIRE_ESM错误
问题描述
更新依赖或重新安装依赖后,执行yarn test(脚本配置为cross-env NODE_ENV=test jest .)或npx jest时触发以下错误:
Error [ERR_REQUIRE_ESM]: require() of ES Module /PROJECT/node_modules/string-width/index.js from /PROJECT/node_modules/cliui/build/index.cjs not supported.
Instead change the require of index.js in /PROJECT/node_modules/cliui/build/index.cjs to a dynamic import() which is available in all CommonJS modules.
直接运行jest可正常执行,但CI/CD依赖npm脚本执行测试无法绕过;在package.json中添加"type": "module"会破坏基于CommonJS的Express服务器。环境信息:Node 18.15.0,NPM 9.8.1,Jest 27.5.1(28.x/29.x版本同样存在该问题)。
解决方案
1. 锁定string-width兼容版本
高版本string-width已改为ESM模块,但依赖它的cliui仍以CommonJS方式加载,导致冲突。通过yarn resolutions或npm overrides锁定兼容的CommonJS版本:
- Yarn用户:在package.json中添加:
"resolutions": { "string-width": "4.2.3" } - NPM用户:在package.json中添加:
"overrides": { "string-width": "4.2.3" }
添加后重新执行yarn install或npm install。
2. 配置Jest转译ESM模块
修改jest.config.js,让Jest转译相关ESM模块为CommonJS格式:
module.exports = { // 保留原有配置内容 transformIgnorePatterns: [ '/node_modules/(?!string-width|strip-ansi|ansi-regex|emoji-regex)' ], transform: { '^.+\\.(js|jsx)$': 'babel-jest' } };
注:确保已安装babel-jest及对应Babel预设(如@babel/preset-env、@babel/preset-react)。
3. 排查环境变量脚本问题
尝试替换cross-env,避免其可能引发的模块加载异常:
- Linux/macOS:将测试脚本改为
NODE_ENV=test jest . - Windows:将测试脚本改为
set NODE_ENV=test && jest .
或升级cross-env到最新版本后重试。
内容的提问来源于stack exchange,提问作者rip

