How tree shaking works - explained with example
Tree shaking is a technique used in modern JavaScript bundlers to eliminate dead code (code that is never used) from the final bundle. This process reduces the size of the output files and improves the performance of web applications by only including the code that is actually used.
How Tree Shaking Works
Tree shaking works by analyzing the dependency graph of a project to determine which pieces of code are actually used. It then removes the unused code during the bundling process. This is particularly effective when using ES6 module syntax (import
and export
), as it allows for static analysis of the code.
Example of Tree Shaking
Consider the following example with a simple utility module:
Utility Module (utils.js
)
// utils.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export function multiply(a, b) {
return a * b;
}
export function divide(a, b) {
return a / b;
}
Main File (main.js
)
// main.js
import { add, subtract } from './utils';
console.log(add(2, 3)); // Output: 5
console.log(subtract(5, 3)); // Output: 2
In this example, only the add
and subtract
functions are used in main.js
. The multiply
and divide
functions are never used and can be considered dead code.
Without Tree Shaking
Without tree shaking, the bundler would include all the functions from utils.js
in the final bundle, even though multiply
and divide
are not used.
With Tree Shaking
With tree shaking, the bundler analyzes the usage of the functions and removes the unused ones. The final bundle will only include the add
and subtract
functions.
Using Tree Shaking with esbuild
Here's how you can use esbuild to perform tree shaking:
-
Install esbuild:
npm install esbuild
-
Create a build script: Create a file called
build.js
:const esbuild = require('esbuild'); esbuild.build({ entryPoints: ['main.js'], bundle: true, outfile: 'dist/bundle.js', minify: true, sourcemap: true, }).catch(() => process.exit(1));
-
Run the build script:
node build.js
Bundler Output
After running the build script with esbuild, the dist/bundle.js
file will only contain the add
and subtract
functions, while the multiply
and divide
functions will be removed from the final bundle.