Angular 12 warning Critical dependency: request of a dependency is an expression

Angular 12 warning Critical dependency: the request of a dependency is an expression

我在 ng build (Angular 12) 后收到这些警告:

./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:35289:13-34 - Warning: Critical dependency: the request of a dependency is an expression

./node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:35301:13-100 - Warning: Critical dependency: the request of a dependency is an expression

我正在使用 @angular-builders/custom-webpack 从初始包中提取 moment.js。

如果我禁用了@angular-builders/custom-webpack,那么一切正常并且警告消失。

此外,如果我在 custom-webpack.config.js 中添加以下内容,警告就会消失:

new webpack.ContextReplacementPlugin(
    /\@angular(\|\/)core(\|\/)__ivy_ngcc__(\|\/)fesm2015/,
    path.join(__dirname, './src'),
    {}
),

请问,究竟是什么导致了这些警告?有没有其他解决方案可以在不像上面那样将插件添加到 webpack 配置的情况下处理它?谢谢

我从 Angular 开发团队得到了以下反馈:

This comes from code in the deprecated SystemJsNgModuleLoader and is normally suppressed when using the CLI builders, which also uses ContextReplacementPlugin. I don't think there is an alternative to suppress them, other than to not suppress them and ignore the warnings.

https://github.com/angular/angular/issues/43092#issuecomment-895848535

所以我最终在 custom-webpack.config.js:

中使用了下面提到的 CLI 构建器代码
// Always replace the context for the System.import in angular/core to prevent warnings.
new ContextReplacementPlugin(
    /\@angular(\|\/)core(\|\/)/,
    path.join(__dirname, '$_lazy_route_resources'),
    {}
),

在 Angular 12 中使用自定义 ContextReplacementPlugin 时,take care about this:

If in your custom configuration you specify a plugin that is already added by Angular CLI then by default the two instances will be merged.

我使用 ContextReplacementPlugin 来 exclude moment.js locales. After upgrading to Angular 12, all locales were removed, because it's config was merged with $_lazy_route_resources。我通过将 replaceDuplicatePlugins 设置为 true.

来解决它