Overview

Tree shaking drops exports that nothing imports, using the static import and export graph of ES modules. Import named functions from ES module builds, avoid barrel files that pull in modules with side effects, and mark packages "sideEffects": false so the bundler can discard what you do not use. Check the bundle analyzer after adding a dependency.

Rules

  • It needs static ES module syntax. CommonJS require is dynamic and cannot be shaken reliably, so a CommonJS-only dependency ships whole.
  • Production builds of Webpack, Rollup, Vite, and esbuild do it automatically; library authors must ship an ESM build and declare sideEffects.
  • It removes code that is never imported. It does not defer code that is used on some routes; that is code-splitting.
// lodash-es is ESM: only debounce is bundled.
import { debounce } from "lodash-es"