Overview
This page is the atomic definition. Bundle optimization lives at nextjs.
Definition
Tree shaking is a dead-code elimination technique that analyzes the static import and export graph of ES modules and removes exports that are never imported anywhere in the application. The term comes from the mental model of shaking a dependency tree so that unused leaves fall off. Bundlers (Webpack with mode: production, Rollup, Vite, esbuild) perform tree shaking automatically when source code uses ES module syntax (import/export). CommonJS (require) cannot be tree-shaken reliably because requires are dynamic. For tree shaking to work, libraries must ship ES module builds and mark themselves "sideEffects": false in package.json. Tailwind CSS performs an analogous pass at the CSS level: its JIT mode scans source files for class names and emits only those classes.
When it applies
Tree shaking works automatically when your bundler is configured for production and your code uses ES module syntax. It fails silently when you import from CommonJS modules, use wildcard imports (import * as foo), or when library authors forget to ship an ESM build.
Example
// lodash-es ships as ESM; only `debounce` is bundled.
import { debounce } from "lodash-es"
// import * from "lodash-es" would include everything.Related concepts
- code-splitting - the complementary technique that splits code into on-demand chunks.
- react - React ships ESM builds suitable for tree shaking.
- tailwind - Tailwind’s JIT is CSS-level dead-code elimination.
- nextjs - Next.js production builds run Webpack/Turbopack tree shaking by default.
- astro - Astro’s zero-JS default reduces the need for tree shaking.
Citing this term
See Tree shaking (llmbestpractices.com/glossary/tree-shaking).