构建或部署Angular+Firebase项目时ESM模块警告的解决方法
执行生产构建命令:
mohammedalfadhel@Mohammeds-Mac-mini app % ng build --configuration production
时出现以下警告:
▲ [警告] 模块'@grpc/grpc-js'被'node_modules/@firebase/firestore/dist/index.node.mjs'引用,但它不是ESM模块
CommonJS或AMD依赖可能会导致优化中断。▲ [警告] 模块'@grpc/proto-loader'被'node_modules/@firebase/firestore/dist/index.node.mjs'引用,但它不是ESM模块
CommonJS或AMD依赖可能会导致优化中断。▲ [警告] 模块'undici'被'node_modules/@firebase/auth/dist/node-esm/index.js'引用,但它不是ESM模块
CommonJS或AMD依赖可能会导致优化中断。▲ [警告] 模块'undici'被'node_modules/@firebase/storage/dist/node-esm/index.node.esm.js'引用,但它不是ESM模块
CommonJS或AMD依赖可能会导致优化中断。
解决方法
1. 配置Angular允许指定CommonJS依赖
在项目根目录的angular.json文件中,找到对应项目的build配置节点,添加allowedCommonJsDependencies数组,将警告中的模块列入其中:
"projects": { "你的项目名称": { "architect": { "build": { "options": { // 保留原有配置 "allowedCommonJsDependencies": [ "@grpc/grpc-js", "@grpc/proto-loader", "undici" ] } } } } }
配置后重新构建,警告会被抑制,同时不影响项目构建结果。
2. 升级Firebase相关依赖
这些警告源于Firebase部分子模块依赖了CommonJS格式的包,升级到Firebase和AngularFire的最新稳定版,可能会解决模块格式不兼容的问题:
npm update firebase @angular/fire
升级完成后重新构建,检查警告是否消失。
3. 验证依赖树(可选)
如果升级后仍有警告,可以使用npm ls命令查看依赖版本,确认是否有嵌套依赖未更新:
npm ls @grpc/grpc-js @grpc/proto-loader undici
若存在旧版本嵌套依赖,可尝试使用npm dedupe来扁平化依赖树。
内容的提问来源于stack exchange,提问作者Alfadhel

