0
0
Angularframework~5 mins

Tree shaking and dead code removal in Angular

Choose your learning style9 modes available
Introduction

Tree shaking helps remove unused code from your Angular app. This makes your app smaller and faster to load.

When you want to reduce the size of your Angular app for faster loading.
When you have many components or services but only use some of them.
When you want to improve app performance by sending less code to the browser.
When you want to keep your app clean by removing unused functions or variables.
Syntax
Angular
No special code is needed. Angular CLI and build tools handle tree shaking automatically during production builds.
Tree shaking works best with ES modules (import/export syntax).
Dead code removal happens during the Angular production build using tools like Webpack and Terser.
Examples
If ComponentB is never used, tree shaking will remove it from the final bundle.
Angular
import { ComponentA } from './component-a';
import { ComponentB } from './component-b';

@Component({ /* ... */ })
export class AppComponent {
  // Only ComponentA is used here
  useComponentA() {
    new ComponentA();
  }
}
The unusedHelper function will be removed during dead code elimination.
Angular
// Unused function
function unusedHelper() {
  console.log('This is never called');
}

// Used function
function usedHelper() {
  console.log('This is called');
}

usedHelper();
Sample Program

In this example, unusedMethod is never called. Angular's build tools will remove it from the final app bundle during production build.

Angular
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<h1>Hello Angular</h1>`
})
export class AppComponent {
  usedMethod() {
    console.log('Used method called');
  }

  unusedMethod() {
    console.log('Unused method');
  }

  constructor() {
    this.usedMethod();
  }
}
OutputSuccess
Important Notes

Always build your Angular app with ng build --prod to enable tree shaking and dead code removal.

Keep your imports clean and avoid importing unused modules to help tree shaking work better.

Summary

Tree shaking removes unused imports and code automatically during production builds.

Dead code removal deletes functions or variables that are never used.

This makes your Angular app smaller and faster to load.