Master Tree Shaking: Eliminate Dead Code and Shrink Your Frontend Bundles

This article explains the principles of Tree Shaking, outlines prerequisites, demonstrates common pitfalls such as CommonJS usage, object aggregation, indirect re‑exports, side‑effect modules, and dynamic properties, and provides practical ways to verify that dead code has been successfully removed from your bundle.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Master Tree Shaking: Eliminate Dead Code and Shrink Your Frontend Bundles

In modern frontend builds, Tree Shaking is a crucial optimization that removes dead code during bundling, reducing bundle size and improving load performance.

What is Tree Shaking?

Tree Shaking is a static analysis technique that eliminates unused ES module exports during the build.

Prerequisites:

Use ES Module syntax ( import / export).

Enable production mode (e.g., mode: 'production' in webpack).

Build tool must support Tree Shaking (Webpack, Rollup, esbuild, Vite, etc.).

How it works

Build tool parses module dependency graph.

Marks which exports are actually referenced.

Removes unreferenced exports (Dead Code Elimination).

Minifier (e.g., Terser) further strips dead statements.

Simple example

// math.js
export function add(a, b) { return a + b; }
export function sub(a, b) { return a - b; }
// main.js
import { add } from './math.js';
console.log(add(2, 3));

After bundling with Tree Shaking, the sub() function is omitted from the final bundle.

Common pitfalls

1. Using CommonJS ( require )

// bad-math.js (CommonJS)
exports.add = (a, b) => a + b;
exports.sub = (a, b) => a - b;
// main.js
const { add } = require('./bad-math');
console.log(add(1, 2));

Problem: Tree Shaking cannot statically analyze CommonJS exports.

Solution: Use ES Module import/export syntax.

2. Exporting an object or array that aggregates many functions

// utils.js
export const utils = {
  a() { console.log('A'); },
  b() { console.log('B'); },
};
// main.js
import { utils } from './utils.js';
utils.a();

Problem: Even though only a() is used, the whole utils object is bundled.

Solution: Export each function individually.

export const a = () => console.log('A');
export const b = () => console.log('B');

3. Indirect re‑exports that hide static paths

// math.js
export const add = (a, b) => a + b;
export const sub = (a, b) => a - b;
// index.js
import * as math from './math.js';
export default math;
// main.js
import math from './index.js';
math.add(1, 2);

Problem: The bundler sees the whole math object and cannot guarantee that sub is unused, so it keeps it.

Solution: Use static re‑exports:

// index.js
export { add, sub } from './math.js';
// main.js
import { add } from './index.js';
add(1, 2);

4. Modules with side effects

// side.js
console.log('I will always run');
export const x = 1;

Problem: Even if x is not used, the module is kept because of the side effect.

Solution: Mark side‑effect‑free modules in package.json with "sideEffects": false, or list the modules that do have side effects.

5. Dynamic property assignments

export const tools = {};
tools['run'] = () => console.log('run');
tools['build'] = () => console.log('build');

Problem: Dynamic property access prevents static analysis, causing the whole tools object to be retained.

Solution: Export a static structure instead.

How to verify Tree Shaking effectiveness

Method 1: Inspect bundle size

Use tools like webpack-bundle-analyzer or source-map-explorer to compare sizes when importing a single function versus the whole library.

Method 2: Inspect generated code

Open the built file and search for functions you expect to be removed; if they are absent, Tree Shaking succeeded.

Summary

Tree Shaking relies on static syntax analysis; understanding its mechanics and following the rules—using ES Modules, avoiding CommonJS, exporting granularly, handling side effects, and avoiding dynamic structures—will help you shrink your bundles and improve performance.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Frontend OptimizationwebpackTree Shakingdead code eliminationES Modules
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.