Use Tree-Shakeable Providers in Angular
Wednesday, February 19, 2020
Use Tree-Shakeable Providers in Angular
Angular version 6 shipped with tree-shakeable providers via the providedIn
option to the @Injectable()
decorator for class that are provided via Angular's dependency injection. Previously, all providers were included in the application's main bundle whether or not the class was necessary. By leveraging this new option we can ensure that only the necessary providers will result in the application's main bundle through the use of tree-shakeable providers.
This affects all Angular versions 6 and greater, including the latest release of Angular, version 9.
Instructions
specify the providedIn
property for the @Injectable()
decorator for providers
the use of the @NgModule()
optional providers
array for tree-shakeable providers
Code Examples
use the providedIn
property of the @Injectable()
decorator
// user.service.ts
import { Injectable } from '@angular/core'
@Injectable({
providedIn: 'root'
})
export class UserService {
// code omitted for brevity
}
// app.module.ts
import { NgModule } from '@angular/core'
@NgModule({
...
providers: []
})
export class AppModule { }
specifying a provider in an Angular module configuration
// user.service.ts
import { Injectable } from '@angular/core'
@Injectable()
export class UserService {
// code omitted for brevity
}
// app.module.ts
import { NgModule } from '@angular/core'
import { UserService } from './services/user.service'
@NgModule({
...
providers: [UserService]
})
export class AppModule { }
Have a question or comment?
So if I use the @ngModule provider decorator's property then Tree-Shakeable wouldn't work as if I use the provideIn property at the @Injectable() decorator?
Yes, that's correct.
In order to perform tree shaking, a static analyzer determines if a symbol is used or not. If you import a class and then specify the class in the
providers
array, then the analyzer will determine that the code is necessary, and will therefore include the code in the resulting bundle/output.