使用 sideEffects 时 Angular 的 Tree shaking 10 shake out AsyncPipe: false

Tree shaking for Angular 10 shook out AsyncPipe when using sideEffects: false

Angular 10 中的摇树是 'shaking' 我的 AsyncPipe。


release notes blog entry for Angular 10 为 ng new 引入了新的 --strict 模式:

这样做的一件事是:

Configures your app as side-effect free to enable more advanced tree-shaking

官方文档说:

When you create projects and workspaces using the strict mode, you'll notice an additional package.json file, located in src/app/ directory. This file informs tools and bundlers that the code under this directory is free of non-local side effects.

这是 package.json 的内容:

{
  "name": "heroes",
  "private": true,
  "description_1": "This is a special package.json file that is not used by package managers.",
  "description_2": "It is used to tell the tools and bundlers whether the code under this directory is free of code with non-local side-effect. Any code that does have non-local side-effects can't be well optimized (tree-shaken) and will result in unnecessary increased payload size.",
  "description_3": "It should be safe to set this option to 'false' for new applications, but existing code bases could be broken when built with the production config if the application code does contain non-local side-effects that the application depends on.",
  "description_4": "To learn more about this file see: https://angular.io/config/app-package-json.",
  "sideEffects": false
}

太棒了!我想。我更喜欢摇树。

然而它摇晃了AsyncPipe,我不知道为什么。我在大型网站的任何地方都使用它 - 我看不出它如何优化它。

它仅在优化的 --prod 版本中执行此操作。当我将其更改为 sideEffects: true 时,它再次起作用。

这是一个known bug with Angular 10 and an issue with Ivy。 当你的组件之间有递归依赖时,它就会发生,例如AComponent 导入 BComponent,但 BComponent 也导入 AComponent

对于导入,重要的是生成的组件代码 - 而不是组件的 Typescript class。 这意味着在您的 AComponent 模板中包含 <app-b-component></app-b-component> 也算作导入 BComponent,因为它在内部引用了 BComponent.

因此当前的 work-around,同时仍然保持更激进的 tree-shaking 和 sideEffects: false,将消除所有递归导入。

我的 Angular 10 应用程序和生产版本(使用 optimization=true,这就是摇树的问题)。

就我而言,那是 DatePipe ({{value | date}}) 坏了。

这会导致区域设置未定义的错误,而它应该是(如果在开发模式下提供应用程序而无需优化,则可以)

ERROR Error: InvalidPipeArgument: 'Missing locale data for the locale "fr".' for pipe 'e'

这里有更多详细信息: