Tree shaking

On this page 7

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.

StageWhat happensTypical tool responsibility
Module resolutionImports are resolved to files and package entry pointsBundler resolver
Graph constructionEvery import and export binding is recordedBundler core
Usage markingReachable exports are flagged from the entry pointsBundler optimizer
Side-effect evaluationModules without used exports are checked for side effectsBundler with package metadata
Dead code removalUnflagged code and unreachable branches are deletedMinifier
Stages of tree shaking in a production build

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.

PatternEffect on tree shakingRecommended handling
Named ES module exportsFully analyzablePreferred export style
CommonJS require and exportsMostly retainedUse an ES module build of the package
Default export of a large objectWhole object retainedExport functions individually
Top-level global mutationModule retained as side effectMove into an explicit init function
CSS imports inside JavaScriptMust be keptList in the sideEffects array
Dynamic property accessPrevents export pruningUse explicit named imports
Code patterns and their effect on tree shaking

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.

TechniqueWhat it removes or changesWhen the benefit appears
Tree shakingUnused exports and modulesEvery page load, smaller total bundle
MinificationWhitespace, comments, long identifiersEvery page load, smaller file size
Code splittingNothing removed, code moved to separate chunksInitial load, code loaded on demand
Lazy loadingDefers loading of noncritical resourcesInitial load and interaction readiness
CompressionRedundancy in transfer encodingNetwork transfer only, not parse cost
How tree shaking differs from neighboring optimizations

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 module field or conditional exports in 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.

SymptomLikely causeFix
Whole library in the bundlePackage ships only CommonJSSwitch to an ES module edition or per-function imports
Unused components retainedBarrel file with side effectsMark the package side-effect free or import directly
Styles missing in productionCSS wrongly treated as pureAdd CSS files to the sideEffects array
No size change after upgradeTranspiler converts modules earlyPreserve ES modules until bundling
Class methods never removedMethods are accessed dynamicallyAccept the limit or refactor to functions
Typical tree shaking failures

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.