如何修复Angular自定义管道文件的CommonJS依赖警告?
问题与解决方案
问题描述
我在angular.json的JS依赖配置中添加了以下模块:
"allowedCommonJsDependencies": ["angular2-wizard", "hammerjs", "moment-timezone"]
但完成Angular全量升级后,我编写的一个使用moment的自定义管道出现了Webpack警告:
[webpack-dev-server] WARNING /Users/mysite/client/src/app/pipes/time-zone.pipe.ts depends on 'moment'. CommonJS or AMD dependencies can cause optimization bailouts.
我尝试将管道文件名time-zone、time-zone.pipe.ts以及管道类名TimeZonePipe加入allowedCommonJsDependencies列表,均无法消除警告。
自定义管道代码如下:
import { Pipe, PipeTransform } from '@angular/core'; import * as moment from 'moment'; @Pipe({ name: 'timeZone' }) export class TimeZonePipe implements PipeTransform { transform(dateUtc: Date, timeZone: string, momentFormat: string, convertJustTimeZone = false): string { const tempDateUtc = moment(dateUtc).utc(true); tempDateUtc.tz(timeZone, convertJustTimeZone); return tempDateUtc.format(momentFormat); } }
解决方法
警告的核心是检测到你直接依赖了CommonJS模块moment,而非你的管道文件或类名。只需将moment本身加入allowedCommonJsDependencies列表即可:
修改angular.json中的配置:
"allowedCommonJsDependencies": ["angular2-wizard", "hammerjs", "moment", "moment-timezone"]
关键说明
allowedCommonJsDependencies的作用是声明允许使用的第三方CommonJS模块,不是用来添加你自己的项目文件或组件类的- 你的管道中明确导入了
moment核心包,虽然已经添加了moment-timezone,但两者是独立的包,需要分别声明 - Webpack的警告是针对
moment这个依赖包,而非你的管道代码,所以添加管道相关名称无效
内容的提问来源于stack exchange,提问作者chuckd
相关产品推荐
相关产品推荐

