Tree Shaking
Tree Shaking
Section titled “Tree Shaking”Introduction
Section titled “Introduction”Tree shaking is dead code elimination — it removes unused exports from JavaScript bundles. The name comes from the idea of shaking a tree to remove dead leaves.
How It Works
Section titled “How It Works”Tree shaking relies on ES module’s static structure — imports and exports are known at compile time, not runtime.
// 📁 utils.jsexport function used() { return 'used'; }export function unused() { return 'never used'; }
// 📁 main.jsimport { used } from './utils.js';// 'unused' is removed during tree shaking 🎯Best Practices
Section titled “Best Practices”// ✅ ES modules (static analyzable)export const value = 42;export function add(a, b) { return a + b; }
// ❌ CommonJS (cannot be tree-shaken)module.exports = { value: 42 };
// ✅ Import only what you needimport { map, filter } from 'lodash-es';
// ❌ Importing the whole libraryimport _ from 'lodash'; // Can't tree-shake
// ✅ Named exports for better tree shakingexport const PI = 3.14;export function circumference(r) { return 2 * PI * r; }
// ❌ Default exports can be harder to tree-shakeexport default { PI, circumference };sideEffects Flag
Section titled “sideEffects Flag”In your package.json, mark modules as side-effect free:
{ "sideEffects": false}Or specify files with side effects:
{ "sideEffects": [ "*.css", "src/polyfills.js" ]}Summary
Section titled “Summary”| Practice | Benefit |
|---|---|
| Use ES modules | Enables tree shaking |
| Named exports | Better optimization |
| Import specific symbols | More dead code removed |
sideEffects: false | Aggressive elimination |
| Avoid CommonJS | Cannot be tree-shaken |