Tree-shakable providers in Angular are a way to make the Angular dependency injection more efficient by allowing unused services to be removed during the build process. Tree-shaking, in general, is an optimization technique used by bundlers like Webpack or Rollup to analyze and eliminate dead code (code not being used) from the final bundle. The purpose is to make the final bundle lighter and improve the application’s load time.
In Angular, before version 6, providers were declared in the ‘@NgModule‘ decorator, like this:
import { MyService } from './my-service';
@NgModule({
providers: [MyService]
})
This way of declaring providers makes it harder for the bundler to determine if the service is used, creating a chance that it will be included in the final bundle even when it is not required.
With tree-shakable providers, you declare the provider using the ‘providedIn‘ property directly inside the ‘@Injectable‘ decorator of the service. This makes it easier for the bundler to identify unused services and remove them from the final bundle.
Here’s an example of a tree-shakable provider:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() { }
}
In this example, the service is provided in the ’root’ injector, which means it will behave as a singleton, available throughout the entire application. By using the ‘providedIn‘ property, you are giving the Angular compiler enough information to make sure the service is included only if it is needed, thus making the final bundle smaller.
Benefits of tree-shakable providers:
1. **Smaller bundle size**: The primary benefit of tree-shakable providers is the reduction of the final bundle size as unused services get removed from the output bundle. This results in faster load and parse times for end-users.
2. **Easier configuration**: Declaring providers inside the ‘@Injectable‘ decorator makes the code more maintainable and easier to understand, as it’s now colocated with the service definition.
3. **Optimized for Ivy**:Tree-shakable providers are recommended and required for Angular Ivy, which is the new rendering engine and has improved tree-shaking capabilities. Ivy won’t interpret providers in ‘@NgModule‘ as tree-shakable by default, so using this approach keeps your code future-proof.
In conclusion, tree-shakable providers in Angular provide a more efficient way to include services in your application while allowing the bundler to eliminate unused services from the final bundle, resulting in a smaller and faster-loading application.