3.5 Hours

7. Tree Shaking: Eliminating Dead Code

Optimization

Tree shaking is the process of removing unused code from the bundle. It's a form of dead code elimination that significantly reduces bundle size. Tree shaking is enabled by ES module imports and exports, which are statically analyzable.

The key insight is that tree shaking works best with ES modules. CommonJS modules are dynamic and harder to analyze. Modern bundlers like Webpack and Vite support tree shaking out of the box. Understanding tree shaking is essential for building efficient applications.

This module covers how tree shaking works, how to enable it, and common pitfalls.

How Tree Shaking Works

Tree shaking works by analyzing the dependency graph at build time. The bundler determines which exports are used and which are not. Unused exports are removed from the final bundle. This reduces bundle size and improves load times.

Tree shaking relies on static analysis. The bundler must be able to determine which exports are used without running the code. This is why ES modules are preferred. CommonJS modules are dynamic, making static analysis difficult. Understanding tree shaking is essential for optimizing bundle size.

Enabling Tree Shaking

Tree shaking is enabled by default in Webpack's production mode and Vite's build command. To maximize tree shaking: use ES modules (import/export), avoid side effects (pure functions), use the sideEffects flag in package.json, and use named exports (not default exports).

The sideEffects flag tells the bundler which files have side effects. Files with side effects cannot be tree-shaken. Setting sideEffects to false in package.json enables aggressive tree shaking.

JavaScript
// package.json - Enable tree shaking
{
  "name": "my-app",
  "sideEffects": false,
  // Or list files with side effects
  "sideEffects": ["*.css", "*.scss"]
}

// Good: Named exports for tree shaking
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const multiply = (a, b) => a * b;

// index.js - Only add is imported
import { add } from './math';
console.log(add(2, 3));
// subtract and multiply are tree-shaken

// Bad: Default exports make tree shaking harder
// math.js
export default {
  add: (a, b) => a + b,
  subtract: (a, b) => a - b,
  multiply: (a, b) => a * b,
};

// index.js - All functions are bundled
import math from './math';
console.log(math.add(2, 3));
// subtract and multiply are included (not tree-shaken)

// Using named exports from a library
// Good
import { debounce } from 'lodash-es';

// Bad
import _ from 'lodash';
const debounce = _.debounce;

// Vite configuration
// vite.config.js
export default defineConfig({
  build: {
    rollupOptions: {
      treeshake: true,
    },
  },
});

Try It Yourself: Tree Shaking

Follow these steps to see tree shaking in action.

Step 1: Create a project with unused code
// src/math.js<br>export function used() {<br> return <strong><code>used;
}

export function unused() {
return unused;
}

export function alsoUnused() {
return also unused;
}

// src/index.js
import { used } from ./math;
console.log(used());

Step 2: Build the project
npm run build

Step 3: Analyze the bundle
Look for unused and alsoUnused in the bundle. They should not be present.

Step 4: Test with a library
npm install lodash-es<br>// src/index.js<br>import { debounce } from <strong><code>lodash-es;
// Only debounce is included

Try It Yourself: Test tree shaking with different export patterns. Compare bundle sizes with and without tree shaking.

Knowledge Check

Ready to test your understanding of 7. Tree Shaking: Eliminating Dead Code?

Back