Answer a Question
Sign In

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

  • Do:

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

  • Avoid:

    the use of the @NgModule() optional providers array for tree-shakeable providers

Avoid

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

Do

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 { }
Brian Love
Brian is a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. He regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, Brian enjoys skiing, hiking, and being in the outdoors. Brian recently launched lookout.dev where you can find best practices and expert advice on topics ranging from TypeScript, Angular, React, Node.js and more.
Google Developers Expert

Whoa 🤚 You need to sign in to join the discussion.

Don't worry, if you start a comment, we'll save it for when you return. 😉