lookout.devlookout.dev
search
Share Knowledge
10

Use Tree-Shakeable Providers in Angular

Wednesday, February 19, 2020

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

checkmark-circle
Do

specify the providedIn property for the @Injectable() decorator for providers

error-circle
Avoid

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 { }
Brian Love

I am a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. I regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, I enjoy skiing, hiking, and being in the outdoors. I started lookout.dev to break down the barriers of learning in public. Learning in public fosters growth - for ourselves and others.

Google Developers Expert

Have a question or comment?

You ·

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?

Brian Love
Brian Love ·

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.