Member-only story

Tree Shaking in Angular.

Venu Vudugula
2 min readOct 16, 2023

--

Tree shaking is a technique used in modern JavaScript build tools like Webpack to eliminate dead (unused) code from your application. In Angular, it’s crucial to optimize the size of your application bundles, leading to faster load times for your web app. Here’s a step-by-step guide with examples to explain how tree shaking works in Angular:

Step 1: Set Up an Angular Project

If you haven’t already, create an Angular project using Angular CLI or your preferred method.

Step 2: Create a Function with Dead Code

Let’s create a simple example to demonstrate tree shaking. In your Angular project, create a TypeScript file, for example, math-functions.ts, with the following code:

export function add(a: number, b: number): number {
return a + b;
}

export function subtract(a: number, b: number): number {
return a - b;
}

export function multiply(a: number, b: number): number {
return a * b;
}

export function divide(a: number, b: number): number {
return a / b;
}

Step 3: Import and Use Functions

In another TypeScript file, let’s say app.component.ts, import and use the functions:

import { add, subtract } from './math-functions';

console.log(add(5, 3));
console.log(subtract(8, 2));

Step 4: Build Your Angular App

Run the following command to build your Angular application in production mode:

ng build --prod

--

--

Venu Vudugula
Venu Vudugula

Written by Venu Vudugula

I'm Venu, a seasoned tech professional with over 9 years of experience in full-stack development, eager to take on exciting challenges 😊.

No responses yet