What is tree shaking in JavaScript?

Sometimes our application gets really large. This is because our application is deployed with both important and unimportant codes.

One way to prevent unused codes in our application is tree shaking.

When we create applications, we sometimes write codes that the application will not directly use (dead codes). The process of creating a bundle that contains only the usable codes is called tree shaking.

Dead code

Suppose, we have three JavaScript functions in a JavaScript file named math.js. These functions are to be imported into the main JavaScript file.

let add = (a, b) => {
return a + b
}
let subtract = (a , b) => {
return a - b;
}
let product = (a,b) => {
return a*b;
}
export{add, subtract, product};

Now, we want to use two of these in our main JavaScript file:

import {add} from './math.js';
import {subtract} from '.math.js';
add(2,3);
subtract(4,5);

The third function, product() is a dead code upon production. The reason is that it is not in use in our application.

Note: Tree shaking is a term commonly used within a JavaScript context to describe dead code removal.

How to utilize tree shaking in JavaScript

There is no traditional way to do tree shaking in modern JavaScript; developers use module bundlers. The most popular bundlers are Webpack and Rollup. These bundlers automatically remove dead codes when bundling multiple JavaScript files into a single file.

Tree shaking with Webpack

Tree shaking with Webpack is very easy. The Webpack development team takes production very important, therefore, making all the best practices easy.

Tree shaking with the updated Webpack version is just one line of code.

webpack --mode=production

The code above will change the status of the webpack.config.js mode to production. Automatically, our project will tree-shake and fully optimize our modules. Dead codes will be eliminated.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved