Tree Shaking: Dropping Dead Code

Tree Shaking: Dropping Dead Code in JavaScript: Imagine you import an entire 300-function utility library just to use one function.

Concept Explanation

Imagine you import an entire 300-function utility library just to use one function. Without help, your users would download all 300. Tree shaking is the bundler grabbing your dependency tree and giving it a hard shake — anything not firmly attached (unused exports) falls off and is left out of the final bundle.

The name is literal: your imports form a tree, and the bundler shakes the dead leaves off. The result is a smaller download and a faster site.


Syntax or Core Structure

// utils.js — exports two functions
export function used() { return "I ship!"; }
export function unused() { return "I get shaken off"; }

// main.js — only imports one
import { used } from "./utils.js";
used();
// After bundling, unused() is NOT in the output.

Tree shaking only works with ES Modules (import/export) because their structure is static — the bundler can see exactly what's used without running the code.


Common Mistakes

  • Using CommonJS: require() is dynamic, so bundlers can't safely shake it. Prefer import.
  • Importing the Whole Library: import _ from "lodash" pulls everything. Use import debounce from "lodash/debounce" or a tree-shakeable build.
  • Side Effects: If a module runs code on import, the bundler keeps it to be safe. Mark packages as side-effect-free in package.json.

Best Practices

  • Import Only What You Need: Named imports (import { x }) beat namespace imports (import * as all).
  • Check Your Bundle: Tools like vite-bundle-visualizer show which dependencies are bloating your build.

Practice Exercises

  1. The Shake Test: Export three functions, import one, build, and confirm the other two vanished.
  2. The Lodash Diet: Replace a full lodash import with a single-function import and compare bundle size.
  3. The Side Effect: Add a console.log at the top level of an unused module and observe whether it still runs after bundling.