Introduction
Tree shaking helps remove unused code from your Angular app. This makes your app smaller and faster to load.
Jump into concepts and practice - no test required
Tree shaking helps remove unused code from your Angular app. This makes your app smaller and faster to load.
No special code is needed. Angular CLI and build tools handle tree shaking automatically during production builds.
import { ComponentA } from './component-a'; import { ComponentB } from './component-b'; @Component({ /* ... */ }) export class AppComponent { // Only ComponentA is used here useComponentA() { new ComponentA(); } }
// Unused function function unusedHelper() { console.log('This is never called'); } // Used function function usedHelper() { console.log('This is called'); } usedHelper();
In this example, unusedMethod is never called. Angular's build tools will remove it from the final app bundle during production build.
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(); } }
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.
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.
unusedMethod() is never called anywhere?export class DataService {
fetchData() { return 'data'; }
unusedMethod() { return 'not used'; }
}