ReactEasy

What is tree shaking?

Tree shaking is dead-code elimination for JavaScript modules: the bundler analyzes static import and export statements and drops exports that are never used from the final bundle. It works with ES modules and is done automatically in production builds by Vite (Rolldown), webpack, Turbopack and esbuild.

Requirements

  • ES modules (import/export): they are static, so the bundler knows at build time what is used. CommonJS (require) is dynamic and largely not shakable.
  • No side effects on import: if importing a module runs code (polyfills, global CSS, registering plugins), the bundler must keep it. Packages declare "sideEffects": false (or a list of files) in package.json to allow removal.
  • Production mode: minifiers remove the unused code.

Habits that help

  • Named imports: import { format } from "date-fns".
  • Import from specific paths when a package lacks good ESM support.
  • Avoid import * as lib combined with dynamic access (lib[name]).
  • Be careful with large barrel files (index.ts re-exporting everything); they can slow builds and sometimes keep extra code.

What it cannot remove

  • Code that is used conditionally at runtime (it cannot know the condition).
  • Side-effectful modules.
  • Unused class methods or object properties in many cases.

Verify

Inspect the bundle with an analyzer, or check that removing an import changes the output size.

Code example

tsx
1// utils/math.ts
2export function add(a: number, b: number) {
3 return a + b;
4}
5export function hugeMatrixInverse(m: number[][]) {
6 // imagine 50KB of code here
7 return m;
8}
9
10// app.ts - only `add` is imported, so hugeMatrixInverse is dropped in production
11import { add } from "./utils/math";
12console.log(add(2, 3));
13
14// Prevents tree shaking: namespace import + dynamic access
15// import * as math from "./utils/math";
16// const fn = (math as Record<string, Function>)[userChoice];
17
18// package.json of a library that is safe to shake
19// { "type": "module", "sideEffects": ["*.css"] }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app