The definite answer to how treeshaking works in practice by example

Baselevel Assumptions:

FINAL_BUNDLE: By FINAL_BUNDLE I mean the result of “ng build --prod”

AllMaterialModul: Contains ALL!! Material Modules + CDK Modules
imports: [MatButtonModule, MatIconModule, …],
exports: [MatButtonModule, MatIconModule, …],

declarations: [EagerComp, EagerPipe],
imports: [AllMaterialModul],
exports: [AllMaterialModul, EagerComp, EagerPipe]

declarations: [AppComponent],
import: [EagerModule]

Case 1:

EagerComp uses mat-stroked-button

AppComponent uses EagerComp

What do I have to pay for (sizewise)?

  • Q1.1: Do I have to pay for eg MatTable stuff, MatIcon stuff … etc. im not using it currently. Im not referencing it anywhere in my templates. (However I imported it in AllMaterialModul )
  • Q1.2: Im using mat-stroked-button so the MatButtonModule has a “HIT”. MatButtonModule exports MatButton, MatAnchor, MatCommonModule,. Will for eg any MatAnchor related data/code be included in my FINAL_BUNDLE. Im not using MatAnchor anywhere, not referencing it.

Case 2:

we define LazyModule in our angular.json > lazyModules array.

declarations: [LazyComp, LazyPipe],
imports: [EagerModule],

LazyComp uses MatTable

Question what “data” will be included in my LazyModule-Chunk.js.

  • Q2.1: As I only use MatTable in LazyModule I expect that only “MatTable stuff” is included in my LazyModule-Chunk.js. So NO MatIcon, LazyPipe, EagerPipe, EagerComp, … Is that true?

I might add other cases later; If you have any good recources to read on that topic Im happy.

Thank you for reading that far.

Can you add more details and context to what you’re trying to understand or achieve? The more you spend time on structuring your questions the more likely you’ll get an answer. Also, please use correct formatting for code blocks.

@santosh.yadav198613 is publishing an article on this very soon.

I discussed it with Matt Vaughn on his Angularlicious podcast recently:

A thing you should be aware of is that the build optimizer tree shakes declarables that you don’t use in templates unless they are entry components in View Engine. However, Angular Material uses many entry components for dynamic rendering and has a few services, some that might not be tree-shakable. They did convert many services to using tree-shakable providers, but there are probably still some exceptions.

Other than that, well set up a demo project with the conditions you describe and disable minification in the build.

Thanks so far for the input. I guess setting up that example project and reading the sources is probably the only real answer. My above question arose by reading your post here on transitive export scopes and stuff. I looking also forward to the article coming.

1 Like