Skip to content
Tree Shaking — Explained with Examples

Tree Shaking — Explained with Examples

DodaTech Updated Jun 15, 2026 1 min read

Tree shaking is dead code elimination that removes unused exports during bundling by statically analyzing ES module imports and exports.

Tree shaking relies on the static structure of ES modules (import/export) — unlike CommonJS’s dynamic require(), ES module dependencies can be determined at compile time. Bundlers like Webpack, Rollup, and esbuild analyze which exports are used and exclude unused code from the final bundle. Side-effect annotations ("sideEffects": false in package.json) help the bundler safely eliminate more code.

Think of tree shaking like shaking a real tree to remove dead leaves. The living leaves (used code) stay attached, while the dead ones (unused exports) fall off. The tree is smaller and healthier after shaking.

For tree shaking to work, imports must use named import syntax rather than namespace imports. Libraries should provide ES module builds with "sideEffects": false in their package.json.

// Good — enables tree shaking
import { Button } from './ui-library';

// Bad — prevents tree shaking (imports everything)
import * as UI from './ui-library';

// Config in package.json
{
  "sideEffects": false,
  // or specify files with side effects:
  "sideEffects": ["*.css"]
}

Tree shaking dramatically reduces bundle sizes. Real-world applications often see 30-60% size reduction after proper tree shaking configuration.

Webpack, Code Splitting, Bundling, Minification

Code Splitting Guide

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro