What Is Tree Shaking?

Tree shaking is a build-time optimization that removes unused exports from the final bundle, based on static analysis of which code is actually imported and...

Published October 7, 2026

Tree shaking is a build step that removes unused exports from your JavaScript bundle, so only the code you actually import ships to users. It relies on ES module static import/export syntax.

The concept

Bundlers (Rollup, webpack, Vite, esbuild) analyse the import graph. If a module exports ten functions and you import one, the other nine can be dropped.

It works best with ES modules and side-effect-free packages (sideEffects: false in package.json). CommonJS require() is dynamic and hard to shake.

Dead code removed

utils.js exports: add, sub, mul, div
app.js imports: add
bundle contains: add (sub, mul, div shaken out)

Practical examples

Import only what you need

import { debounce } from 'lodash-es'   // good
// import _ from 'lodash'               // pulls everything

Mark a package side-effect free

{ "sideEffects": false }

Check bundle size

npx vite-bundle-visualizer
npx source-map-explorer dist/*.js

Common mistakes

  • Importing from CommonJS packages and expecting shaking.
  • Barrel files that import everything with side effects.
  • Code with top-level side effects the bundler cannot remove.

Key takeaways

  • Unused exports are dropped at build time.
  • Needs ES modules.
  • Prefer modular libraries.

FAQ

Is tree shaking automatic?

In production builds of modern bundlers, yes, when code is shake-friendly.

Does it work for CSS?

Tools like Tailwind and PurgeCSS remove unused CSS in a similar spirit.

More JavaScript articles