Tree shaking

Your bundler deletes the exports nothing imports, so a huge library ships as only the handful of functions you actually call.

strip out code I never callremove the dead library partsdead code eliminationtreeshakingtree shakerdrop unused exportswhy does importing one function pull in the whole library

See it

Live demo coming soon

What it is

Tree shaking is your bundler walking the import graph, marking every export nothing reaches, and deleting it before the file ships. Import one date helper from a 70kb library and, in the good case, the browser gets that one helper. The name comes from shaking a tree until the dead leaves fall off.

It works best on ES modules, because 'import' and 'export' can be read statically without running the code. CommonJS 'require()' is decided at runtime, so bundlers fall back to guessing and usually keep everything to be safe. Modern bundlers can still eliminate some CommonJS when the shape is obvious enough to analyse, so this is a reliability difference, not a hard wall. The other half of the deal is the 'sideEffects' field in package.json: it is the library author promising that importing a file does nothing on its own, which frees the bundler to drop untouched modules entirely.

The classic disappointment: you tree shake, the bundle barely moves. Usual culprits are a CommonJS-only dependency, a package with no 'sideEffects' declaration, or a barrel file that drags in modules which do real work on import. Note that 'import * as X' and barrels are not automatically fatal: when the graph stays statically analysable and side-effect free, a good bundler still drops what you never touch. They just make it much easier for one stray side effect to pin the whole tree in place. Check with a bundle analyzer before blaming the config, and prefer libraries that publish real ESM builds.

Ask AI for it

Make this bundle tree shakeable. Convert the package to ES modules (type: 'module', ESM output from the build), replace every 'import * as X' and barrel-file re-export that pulls in side-effectful modules with direct named imports from the specific module path, add a 'sideEffects' field to package.json listing only the files that genuinely have side effects (CSS imports, polyfills), and swap any CommonJS-only dependency for an ESM equivalent where one exists. Measure after each step rather than assuming: run a bundle analyzer and report the before and after size for each chunk.

You might have meant

bundle sizecode splittingunused javascript cssbundle analyzerminification

Go deeper