Ilya Chernomordik Ilya Chernomordik - 6 months ago 56
TypeScript Question

Do we need tree-shaking with webpack and typescript / angular2?

I have followed the tutorial to add webpack to Angular from here. If I understand correctly we feed the main module to webpack and then it traverses the whole tree and adds all the referenced files to the bundle. I have also read that we can optimize this by using tree-shaking.

What I don't understand here is why do we need tree-shaking if webpack already scans for only "used" modules (i.e. the ones we "import").

Does tree-shaking do something additional (like checking the classes from the modules that are not used and removing them from the module even though it's imported?) or I misunderstand the concept alltogether?


As mentioned in the comments, the real benefit is that it can remove some code from the files, while without tree-shaking there will be the whole module in the result even if just one of the exported classed are used.



export class AppComponent {

    test(): void {

export class AppComponentDeadCode {

    test(): void {


import { AppComponent } from './app.component';

Now in this example we never import AppComponentDeadCode class.

  • Without tree-shaking both of the classes will be in the resulting module/bundle.
  • With tree-shaking the class AppComponentDeadCode will be removed from the resulting module/bundle (considering there are no other modules that import it).

P.S. Unfortunately the state of this shiny toy is quite "beta" and it's hard to achieve the result easily if at all with typescript/angular2. More information about it here.