开发Angular库时,能否在ngPackagr中配置allowedCommonJsDependencies?
解决Angular库依赖CommonJS导致使用者警告的问题
ngPackagr本身没有提供和Angular CLI中allowedCommonJsDependencies完全对应的配置项,但可以通过以下两种方式解决使用者遇到的警告问题:
方式一:指引使用者手动配置
直接告知库的使用者,在他们项目的angular.json的build.options中添加allowedCommonJsDependencies字段,将你的库所依赖的CommonJS包(比如moment)加入列表:
"build": { "builder": "@angular-devkit/build-angular:browser", "options": { "allowedCommonJsDependencies": [ "moment" ] // 其他配置... } // 其他配置... },
方式二:优化库的依赖处理 推荐
从根源上避免使用者出现警告,建议做以下优化:
- 改用ESM格式的依赖包:替换掉CommonJS格式的依赖,比如用
date-fns(原生ESM支持)替代moment,或者使用moment-es6这类ESM版本的包; - 构建时转换CommonJS依赖:利用ngPackagr底层的Rollup配置,在
ng-package.json中添加Rollup插件将CommonJS依赖转换为ESM。示例配置:
{ "$schema": "./node_modules/ng-packagr/ng-package.schema.json", "lib": { "entryFile": "src/public-api.ts", "umdModuleIds": { "moment": "moment" } }, "rollupConfig": { "plugins": [ "@rollup/plugin-commonjs" ] } }
注意需要先安装@rollup/plugin-commonjs依赖。
内容的提问来源于stack exchange,提问作者Mikelgo
相关产品推荐
相关产品推荐

