Introduction
In modern web development, performance plays a crucial role in delivering a smooth user experience. One of the biggest factors that affects performance is the size of your JavaScript bundle. Larger bundles take more time to download, parse, and execute in the browser.
This is where tree shaking in JavaScript becomes important.
Tree shaking is a technique used by modern build tools like Webpack, Rollup, and Vite to remove unused code from your final bundle. By eliminating unnecessary code, it helps reduce bundle size, improve loading speed, and optimize overall application performance.
In this article, we will explore what tree shaking is, how it works, and how it helps reduce bundle size in JavaScript applications.
What is Tree Shaking in JavaScript?
Tree shaking is a process of removing unused (dead) code from JavaScript files during the build process.
Concept Explanation
Imagine your code as a tree:
Each function or module is a branch
Only the branches that are used are kept
The unused branches are removed
This process ensures that only the required code is included in the final output.
Why It Matters
Reduces JavaScript bundle size
Improves website loading speed
Enhances performance
Saves bandwidth
How Tree Shaking Works
Tree shaking works based on static analysis of ES6 modules (ES Modules).
Key Requirement: ES Modules
Tree shaking only works effectively with import and export syntax.
// math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
// app.js
import { add } from "./math.js";
console.log(add(2, 3));
Code Explanation
math.jsexports two functions:addandsubtractapp.jsimports onlyaddDuring build,
subtractis removed because it is not used
This is the core idea behind tree shaking.
Why ES Modules Are Important
ES Modules allow build tools to understand dependencies at compile time.
Example
import { add } from "./math.js";
Code Explanation
This import is static and predictable
Bundlers can analyze which parts are used
What Does NOT Work
const math = require("./math");

Join the conversation! Your thoughts help the community grow.