Search code examples
angulartree-shaking

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


Tree shaking in Angular 10 is 'shaking' out my AsyncPipe.


The release notes blog entry for Angular 10 introduces a new --strict mode for ng new:

One thing this does is:

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

The official documentation says:

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.

Here's the content of that 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
}

Great! I thought. I love more tree shaking.

However it shook away AsyncPipe and I don't know why. I use it everywhere in a large website - and I don't see how it could possibly have optimized it away.

It only did this in an optimized --prod build. When I changed it to sideEffects: true it worked again.


Solution

  • This is a known bug with Angular 10 and an issue with Ivy. It happens when you have recursive dependencies between your components, e.g. AComponent imports BComponent, but BComponent also imports AComponent.

    For importing, what matters is the generated component code - not the Typescript of your component class. That would mean having <app-b-component></app-b-component> in your AComponent's template also counts as importing BComponent, because internally it references BComponent.

    So the current work-around, while still keeping the more aggressive tree-shaking with sideEffects: false, would be to eliminate all recursive imports.