Tree shaking is a technique used in modern JavaScript frameworks to remove unused code from the build process, thus leading to smaller bundle sizes and better application performance. Angular supports tree shaking through Injectable Services and Modules, ensuring only necessary code makes it into final builds. This article explains tree shaking in Angular, how it works, and best practices for creating tree-shakable services and modules.
Tree shaking is a dead code elimination process that removes unused code from the final JavaScript bundle. Angular applications use tree shaking to optimize performance by discarding unused services, components, and modules.
For example, if you have an Angular service that is never injected into any components, the Angular build process (through Webpack and Terser) will detect and remove it from the final bundle.
Angular achieves tree shaking primarily through the `providedIn` property in the `@Injectable()` decorator, which determines how services are registered in the dependency injection system.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' // Ensures tree-shakability
})
export class ExampleService {
constructor() { }
logMessage() {
console.log('Tree-Shakable Service!');
}
}
This approach ensures `ExampleService` is application-wide but only included if actually used. If never referenced, it will be tree-shaken.
@Injectable({
providedIn: 'any'
})
export class LazyService {
constructor() { }
}
Introduced in Angular 9, this ensures services in lazy-loaded modules aren't included in the initial bundle.
@NgModule({
providers: [ExampleService]
})
export class SomeModule {}
This traditional method isn't tree-shakable - the service will always be included even if unused.
Angular modules can also be optimized for tree shaking when implemented correctly.
Declaring providers directly in NgModules prevents effective tree shaking. Always prefer `providedIn`.
import { Component } from '@angular/core';
@Component({
selector: 'app-standalone',
standalone: true,
template: `<p>Standalone Component</p>`
})
export class StandaloneComponent {}
Angular 14+ standalone components eliminate NgModule dependencies, improving tree shaking efficiency.
const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
}
];
Tree shaking is a powerful Angular optimization technique that removes unused code to improve performance. By implementing tree-shakable services (using `providedIn`), lazy loading, and standalone components, you can significantly reduce bundle sizes and enhance load times. Understanding and applying these patterns leads to more efficient, maintainable Angular applications with better runtime performance. Start optimizing your Angular projects today!
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.