Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท Optimization and Caching

Tree Shaking and Side Effects

Understand webpack tree shaking: how usedExports and the sideEffects flag remove unused code, why ES modules matter, and the mistakes that keep dead code in your bundle.

If you import one function from a utility library, do you ship the whole library? With tree shaking the answer can be no: the bundler works out which exports nothing ever uses and drops them. The name comes from the picture of shaking a tree so the dead leaves fall off. It is one of the largest bundle-size wins in a modern build, and one of the most misunderstood, because it only works when several conditions are met.

This lesson explains the two parts of the mechanism, how the sideEffects flag works, and the usual reasons tree shaking silently fails.

Webpack is not runnable on the site. The TryIt blocks are Node.js stand-ins that implement the core idea (an export-usage analysis) in a few lines. Real webpack and Terser do this on a full syntax tree.

Two steps, two tools

Tree shaking in webpack is a partnership.

  1. Marking. With optimization.usedExports (on in production), webpack analyses every ES module and records which exports are used. Unused exports get a comment like /* unused harmony export helper */ in the generated code, but are still there.
  2. Deleting. The minifier (Terser) then removes the code that is no longer referenced. That is why you will not see shrinkage in development mode: nothing deletes the marked code.

On top of that, the sideEffects setting lets webpack skip whole modules, not just single exports.

flowchart LR
  A["Import graph"] --> B["usedExports:<br/>mark unused exports"]
  B --> C["sideEffects:<br/>skip unused modules"]
  C --> D["Terser:<br/>delete dead code"]

The path from import graph to a smaller bundle.

Why ES modules are required

Static import and export can be analysed without running code: the names are literal strings known at build time. CommonJS require() is a normal function call, so const lib = require(name) could return anything. Webpack cannot prove what is unused, so it keeps the entire module. Consequences:

  • Prefer libraries that publish an ES module build (look for "module" or "exports" with an import condition in their package.json).
  • Make sure Babel is configured to keep ES modules (modules: false in @babel/preset-env), otherwise it rewrites them to CommonJS before webpack sees them.
  • Avoid export default { a, b, c } objects for utility collections; a default object is a single value that cannot be partly dropped. Use named exports.

A stand-in for the marking step

This stand-in reads module sources with a regex, finds exported names, and reports which ones the importers never use.

Node.js Stand-in: find unused exports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

sub, mul and whisper are never imported, so a real build would remove them from the final bundle.

Side effects

There is a catch. Removing an unused export is safe, but removing a whole module is only safe if merely importing it does nothing. A module has a side effect if running its top-level code changes something outside itself: it registers a global, patches a prototype, injects CSS, or logs. Consider:

JavaScript
// analytics.js
window.analytics = createTracker();   // side effect at import time
export function track(name) { /* ... */ }

import './analytics.js' with no names looks useless but is not. Webpack must assume any module might have side effects unless told otherwise. You tell it in package.json:

JSON
{
  "name": "my-ui-library",
  "sideEffects": false
}

"sideEffects": false promises that every file in the package is pure, so if none of its exports are used, the entire module may be skipped. Most libraries are pure, but the flag is dangerous in an application where you import CSS or polyfills. Use an array to list the exceptions:

JSON
{
  "sideEffects": ["*.css", "./src/polyfills.js"]
}

If you set false while a file really has side effects, that file silently stops running in production and you get bugs that never appear in development. Always list CSS imports and polyfills.

Node.js Stand-in: pure versus side-effectful modules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Common reasons tree shaking fails

Symptom Cause Fix
Whole library included CommonJS build only Use the library's ES build or an alternative such as lodash-es
No effect in dev Marking without deletion Check with mode: 'production'
import * as ns keeps everything Dynamic property access like ns[name] Use named imports
Class methods remain Methods cannot be removed individually Split into functions, or accept it
Code with /*#__PURE__*/ missing Terser cannot prove a call is pure Add the annotation (compilers often do)
Babel output is CommonJS modules not false Configure @babel/preset-env with modules: false

The /*#__PURE__*/ annotation marks a function call as side-effect free, so if its result is unused, the call can be dropped. Libraries and compilers add it to code like /*#__PURE__*/ createStore().

Checking the result

Never assume. Build, then search the output for a name you expect to be gone, or open the bundle analyzer and check that the library you import from is as small as you expect. Setting optimization.usedExports: true together with optimization.minimize: false lets you read the unused-export comments in a production-like build, which is a good way to debug.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is tree shaking more effective with ES modules than with CommonJS?

    require() can be called with computed values, so webpack cannot prove which exports are unused. Static imports can be analysed.
  2. 2. What does "sideEffects": false in a package.json promise?

    It tells webpack that modules of the package are pure, so unused ones can be dropped entirely.
  3. 3. You add "sideEffects": false to your app and your global CSS stops appearing in production. What is the fix?

    A CSS import has no used exports, so webpack drops it unless you list it as having side effects.
  4. 4. In which step is code actually deleted?

    usedExports only marks unused exports. The minifier deletes the unreferenced code, which is why shrinkage shows up in production builds.

Summary

  • Tree shaking marks unused exports and then lets the minifier delete them.
  • It needs static ES module syntax; CommonJS and ns[name] defeat it.
  • sideEffects lets webpack skip entire pure modules; list CSS and polyfills as exceptions.
  • Use named exports, keep Babel from rewriting modules, and verify the output.

Next: Long-Term Caching with Content Hashes