Tree shaking is a build-time optimization in which a module bundler removes code that is exported but never imported or used, so the final JavaScript bundle contains only the parts of each module that the application actually reaches. In web performance, it is one of the main techniques for reducing bytes shipped to the browser, and therefore the time spent downloading, parsing, compiling and executing scripts.
The name describes the idea of shaking a dependency tree until the dead leaves fall off. Strictly speaking, tree shaking is a form of dead code elimination that works on the module graph rather than on individual statements, and it relies on the static structure of ECMAScript modules to decide what can be safely dropped.
How tree shaking analyzes the module graph
Tree shaking works by building a graph of imports and exports starting from the entry points of an application and marking every binding that is reachable. Exports that are never marked are excluded from the output, and a minifier then removes any leftover code that has become unreachable.
The technique depends on static import and export declarations. An import { debounce } from "utils" statement is visible at build time, so the bundler knows that only debounce is needed. A CommonJS require() call, by contrast, can be computed at runtime and assigned to arbitrary objects, which makes precise analysis unreliable or impossible in the general case.
Most bundlers split the process into two phases. The first phase is usage marking, which flags unused exports during graph construction. The second phase is dead code removal, usually performed by a minifier such as Terser or esbuild, which deletes the flagged code and anything that only it referenced.
The following table summarizes the stages that a typical production build passes through.
| Stage | What happens | Typical tool responsibility |
|---|---|---|
| Module resolution | Imports are resolved to files and package entry points | Bundler resolver |
| Graph construction | Every import and export binding is recorded | Bundler core |
| Usage marking | Reachable exports are flagged from the entry points | Bundler optimizer |
| Side-effect evaluation | Modules without used exports are checked for side effects | Bundler with package metadata |
| Dead code removal | Unflagged code and unreachable branches are deleted | Minifier |
Side effects and why they block removal
A side effect is any code that does something observable when a module is evaluated, such as modifying a global object, registering a polyfill or injecting CSS. A bundler must keep such code even when no export is used, because removing it could change program behavior.
Because a bundler cannot always prove that code is pure, it acts conservatively. Package authors help by declaring the `sideEffects` field in package.json: setting it to false tells tools such as webpack and Rollup that unused modules from the package may be dropped entirely, while an array lists the files that must always be kept, such as stylesheets.
Developers can also annotate individual calls with the `/*#__PURE__*/` comment, which signals that a function call has no side effects and may be removed if its result is unused. This annotation is common in compiled output from frameworks and transpilers, where class wrappers would otherwise look impure to the minifier.
The table below lists common patterns and how they affect the ability to remove code.
| Pattern | Effect on tree shaking | Recommended handling |
|---|---|---|
| Named ES module exports | Fully analyzable | Preferred export style |
| CommonJS require and exports | Mostly retained | Use an ES module build of the package |
| Default export of a large object | Whole object retained | Export functions individually |
| Top-level global mutation | Module retained as side effect | Move into an explicit init function |
| CSS imports inside JavaScript | Must be kept | List in the sideEffects array |
| Dynamic property access | Prevents export pruning | Use explicit named imports |
Tree shaking compared with related techniques
Tree shaking is one of several complementary methods for reducing JavaScript payload, and it is often confused with minification and code splitting. Each technique addresses a different source of waste, and a well-tuned build normally applies all three together.
| Technique | What it removes or changes | When the benefit appears |
|---|---|---|
| Tree shaking | Unused exports and modules | Every page load, smaller total bundle |
| Minification | Whitespace, comments, long identifiers | Every page load, smaller file size |
| Code splitting | Nothing removed, code moved to separate chunks | Initial load, code loaded on demand |
| Lazy loading | Defers loading of noncritical resources | Initial load and interaction readiness |
| Compression | Redundancy in transfer encoding | Network transfer only, not parse cost |
The distinction matters for metrics. Compression such as Brotli reduces transfer time, but the browser still has to parse and compile the decompressed code. Tree shaking reduces the code itself, which lowers main-thread work and helps metrics such as Total Blocking Time and Interaction to Next Paint (INP) on low-end mobile devices.
Configuring a build for effective tree shaking
Effective tree shaking requires that ES module syntax survives until the bundler sees it. If a transpiler such as Babel converts modules to CommonJS before bundling, the static structure is lost. Setting the transpiler to preserve modules, for example with modules: false in a Babel preset, is therefore a first configuration check.
Production mode in webpack enables usedExports and minification automatically, while Rollup, esbuild and Vite perform tree shaking by default. Developers should still verify the result, because a single impure import can pull in an entire library.
- Prefer packages that publish ES module builds, indicated by the
modulefield or conditionalexportsin package.json. - Import specific functions rather than whole namespaces when a library is not well structured.
- Inspect the output with a bundle analyzer to find modules that remain despite being unused.
- Track bundle size in a performance budget so that regressions are caught in continuous integration.
Limitations and common mistakes
Tree shaking is not a guarantee of a lean bundle. Its result depends on how libraries are written, how the build is configured and how the application imports code. Savings range from negligible in already modular codebases to tens of percent when large utility or component libraries are imported carelessly.
The most frequent problems and their remedies are summarized below.
| Symptom | Likely cause | Fix |
|---|---|---|
| Whole library in the bundle | Package ships only CommonJS | Switch to an ES module edition or per-function imports |
| Unused components retained | Barrel file with side effects | Mark the package side-effect free or import directly |
| Styles missing in production | CSS wrongly treated as pure | Add CSS files to the sideEffects array |
| No size change after upgrade | Transpiler converts modules early | Preserve ES modules until bundling |
| Class methods never removed | Methods are accessed dynamically | Accept the limit or refactor to functions |
A further limit is granularity. Most bundlers remove unused exports, but they rarely remove unused methods from a class or unused properties from an exported object. Libraries designed for function-level imports therefore shake far better than those built around one large object.
A plain-language summary
Websites are built from many small pieces of code, often borrowed from large shared libraries. Usually a site needs only a few pieces from each library, but without care the whole library is sent to every visitor.
Tree shaking is a step that happens before the site goes live. A tool checks which pieces are really used and leaves the rest out. It is like packing for a trip by taking only the clothes on the itinerary instead of the entire wardrobe. The key takeaway is simple: less unused code means faster pages, especially on phones.
An example from practice
A front-end team at an online retailer notices that the product page ships about 480 KB of minified JavaScript and scores poorly on Total Blocking Time on mid-range Android phones. A bundle analyzer shows that an entire date utility library and a full icon set are included, although the page uses four date functions and twelve icons.
The team replaces the CommonJS build of the date library with its ES module edition, imports icons individually instead of through a barrel file and marks its internal design system package with "sideEffects": ["*.css"]. It also fixes a Babel setting that was converting modules to CommonJS before bundling.
After the changes, the product page bundle drops to roughly 300 KB minified. Lab tests show noticeably lower main-thread blocking time, and the team adds a performance budget to continuous integration so that the savings are not lost in later releases.