使用 sideEffects 时,Angular 10 的 Tree Shaking 晃动了 AsyncPipe:false

Sim*_*ver 7 tree-shaking angular

Angular 10 中的树摇晃正在“摇晃”我的 AsyncPipe。


Angular 10的发行说明博客条目引入了一种新--strict模式ng new

这样做的一件事是:

将您的应用程序配置为无副作用以启用更高级的摇树

官方文档说:

当您使用严格模式创建项目和工作区时,您会注意到位于 src/app/ 目录中的额外 package.json 文件。该文件通知工具和打包器该目录下的代码没有非本地副作用。

这是其中的内容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
}
Run Code Online (Sandbox Code Playgroud)

伟大的!我想。我更喜欢摇树。

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

它只在优化的--prod构建中做到了这一点。当我把它改成它时,sideEffects: true它又工作了。

Mar*_*olt 2

这是Angular 10 的一个已知错误,也是Ivy 的一个问题。当您的组件之间存在递归依赖关系时,就会发生这种情况,例如AComponent导入BComponent,但BComponent也导入AComponent

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

因此,当前的解决方法sideEffects: false是消除所有递归导入,同时仍然保持更积极的树摇动。