Tree shaking vs. Non tree shaking providers in Angular
Piyali Das
11+ yrs | Angular (Core + Material UI + AgGrid) | Nx Monorepo | NGRX | RXJS | GraphQL | TypeScript | JavaScript | SASS
In our example we are importing and referencing our Service in the AppModule causing an explicit dependency that cannot be tree shaken.
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { SharedService } from './shared.service'; @NgModule({ imports: [BrowserModule, FormsModule], declarations: [AppComponent], bootstrap: [AppComponent], providers: [SharedService] })
export class AppModule {}
By using tree shaking, we can make sure our application only includes the code that is needed for our application to run.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class SharedService { constructor() { console.log('SharedService instantiated'); }
}