Home > Back-end >  How to fix CommonJS dependency warning on custom pipe file in Angular?
How to fix CommonJS dependency warning on custom pipe file in Angular?

Time:02-03

I've added a couple of modules to my angular.json JS dependencies section like this:

"allowedCommonJsDependencies": ["angular2-wizard", "hammerjs", "moment-timezone"]

But I just upgraded everything and I'm getting another warning about a pipe I created that uses moment:

[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.

I tried adding the .ts filename to the list like below but I'm still getting the warning.

"allowedCommonJsDependencies": ["angular2-wizard", "hammerjs", "moment-timezone", "time-zone"]

I also tried: "time-zone.pipe.ts" and "TimeZonePipe" which is the name of the class, but none seem to remove the warning.

How can I fix this?

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);
  }

}

CodePudding user response:

As already mentioned momentjs is a CommonJS module, tree-shaking does not work well on CommonJS modules, that is why you got warning. See official link from Angular docs How CommonJS is making your bundles larger.

So you have only two options: ignore this warning and continue using momentjs hoping that in the future they move to es6 modules or switch to another library like luxon.

  • Related