Web Fundamentals

Tree Shaking: Eliminate Dead Code from Your Bundle

easyWeb Fundamentals

Tree Shaking: Eliminate Dead Code from Your Bundle

Learn the interview-ready mental model, practical trade-offs, and production patterns for this web fundamentals topic.

Topic content

TL;DRUse ES modules + named imports + sideEffects: false. Only ship code that is actually used.
High Signal
Google
Meta
Netflix
Agoda
Meesho
30-Second Answerstart every interview with this

Tree shaking is a build-time optimization where bundlers (Webpack, Vite, Rollup) automatically remove unused exports from your JavaScript bundles. It relies on static analysis of ES6 module syntax and proper configuration to maximize reduction in bundle size.

You tell the packer exactly what you need (named imports). The packer looks at your list and only puts those items in the suitcase. Anything you didn't explicitly ask for (unused exports) gets left behind — saving space and weight.

Import Statement (What you need)
Bundler Static Analysis
Mark Unused Exports
Remove Dead Code
Smaller Final Bundle

1How Tree Shaking Works

Bundlers perform static analysis on ES6 import/export syntax to determine which exports are used. Unused code is eliminated during the build process.

utils.tsts
export function add(a: number, b: number) { return a + b; }
export function subtract(a: number, b: number) { return a - b; }

// Only add is imported → subtract is removed

2Writing Tree-Shakeable Code

Use ES modules, named exports, avoid side effects, and prefer libraries designed for tree shaking (lodash-es, date-fns).

3Package Configuration

Mark packages as side-effect-free with `"sideEffects": false` in package.json. Use the `module` or `exports` field for modern bundlers.

4Verification

Use webpack-bundle-analyzer or Vite's visualizer to inspect what actually ends up in your final bundle.

Key Takeaways
  • Tree shaking requires ES6 modules and named imports
  • Mark side-effect-free packages with "sideEffects": false
  • Prefer lodash-es, date-fns, and modular libraries
  • Use bundle analyzer to verify results regularly
  • Tree shaking is most effective when combined with code splitting
  • Write code with bundle size in mind from the start