What is tree shaking and what conditions must be met for it to work?
Tree shaking is the process of removing unused exports from a bundle by statically analyzing which imports are referenced.
Conditions required:
- ES Modules (ESM) —
import/exportare statically analyzable. CommonJSrequire()is dynamic so bundlers can't determine what's used at build time. sideEffects: falsein package.json — tells the bundler it's safe to drop any module that isn't imported. Without this, bundlers assume every module might have side effects (e.g., polyfills modifying globals).- No dynamic import patterns —
import(variable)defeats static analysis. - Bundler support — Webpack, Rollup, esbuild, Vite all support tree shaking by default for ESM.
// utils.ts — only 'add' is imported, 'multiply' will be shaken out
export function add(a: number, b: number) { return a + b; }
export function multiply(a: number, b: number) { return a * b; }
// index.ts
import { add } from './utils'; // multiply never bundled
import { Button } from '@ui') can defeat tree shaking if the barrel re-exports from CommonJS modules. Prefer deep imports for large libraries.