Angular项目启动报错:不支持ES Module的require()调用
问题详情
运行ng serve后触发以下错误:
An unhandled exception occurred: require() of ES Module C:\Users*\Documents\GitHub*\node_modules@angular\compiler\fesm2015\compiler.mjs not supported.
Instead change the require of C:\Users*\Documents\GitHub******\node_modules@angular\compiler\fesm2015\compiler.mjs to a dynamic import() which
is available in all CommonJS modules.
See "C:\Users*\AppData\Local\Temp\ng-0FyohJ\angular-errors.log" for further details.
已执行的排查操作
- 运行
npm outdated检查包版本,核心Angular包当前版本与期望版本匹配,但存在关键依赖版本不一致 - 尝试排查node-fetch相关问题,未解决
- 更新npm并清理缓存,无效
npm outdated输出结果:
PS C:\Users\mjbaldwin\Documents\GitHub\****> npm outdated Package Current Wanted Latest Location Depended by @angular-devkit/build-angular 13.3.8 13.3.8 14.0.5 node_modules/@angular-devkit/build-angular **** @angular/animations 13.3.11 13.3.11 14.0.5 node_modules/@angular/animations **** @angular/cli 9.0.7 9.0.7 14.0.5 node_modules/@angular/cli **** @angular/common 13.3.11 13.3.11 14.0.5 node_modules/@angular/common **** @angular/compiler 13.3.11 13.3.11 14.0.5 node_modules/@angular/compiler **** @angular/compiler-cli 9.0.7 9.0.7 14.0.5 node_modules/@angular/compiler-cli **** @angular/core 13.3.11 13.3.11 14.0.5 node_modules/@angular/core **** @angular/forms 13.3.11 13.3.11 14.0.5 node_modules/@angular/forms **** @angular/language-service 13.3.11 13.3.11 14.0.5 node_modules/@angular/language-service **** @angular/platform-browser 13.3.11 13.3.11 14.0.5 node_modules/@angular/platform-browser **** @angular/platform-browser-dynamic 13.3.11 13.3.11 14.0.5 node_modules/@angular/platform-browser-dynamic **** @angular/router 13.3.11 13.3.11 14.0.5 node_modules/@angular/router **** @types/jasmine 3.10.6 3.10.6 4.0.3 node_modules/@types/jasmine **** @types/node 17.0.45 17.0.45 18.0.3 node_modules/@types/node **** karma-jasmine 4.0.2 4.0.2 5.1.0 node_modules/karma-jasmine **** karma-jasmine-html-reporter 1.7.0 1.7.0 2.0.0 node_modules/karma-jasmine-html-reporter **** node 17.9.1 17.9.1 18.5.0 node_modules/node **** node-fetch 2.6.7 2.6.7 3.2.6 node_modules/node-fetch ****
解决方案
1. 修复Angular CLI与核心包版本不兼容
从版本列表可以看到,@angular/cli和@angular/compiler-cli停留在9.0.7,但其他Angular核心包已经升级到13.3.11,版本严重不匹配是触发ES模块错误的核心原因。执行以下命令将CLI和compiler-cli升级到与核心包一致的版本:
npm install @angular/cli@13.3.11 @angular/compiler-cli@13.3.11 --save-dev
2. 清理并重新安装依赖
更新完成后,清理旧依赖文件并重新安装:
# macOS/Linux rm -rf node_modules package-lock.json npm install # Windows rmdir /s /q node_modules && del package-lock.json npm install
3. 调整Node.js版本到兼容范围
Angular 13官方推荐使用Node.js 14.x或16.x LTS版本,当前使用的17.9.1属于非稳定版,可能存在兼容性问题。建议通过nvm切换到16.x版本:
# 安装nvm后执行 nvm install 16 nvm use 16
4. 锁定node-fetch版本
node-fetch 3.x为纯ES模块,可能与项目的CommonJS环境冲突,当前使用的2.6.7是兼容版本,无需升级。若之前误升级,可执行以下命令回退:
npm install node-fetch@2.6.7 --save
内容的提问来源于stack exchange,提问作者M. Bal.

