Course contentsShow
← Web Development
Lesson 1415 of 2,98225. Build Tools and BundlersFree lesson

What is Tree Shaking?

Understanding how bundlers eliminate unused exports from your final bundle.

What is Tree Shaking?

You'll learn how bundlers automatically remove unused code from your final JavaScript bundle to keep it lean and fast.

The Core Idea

Tree shaking is a process where your bundler (like Vite, Webpack, or Rollup) analyzes your code and eliminates any exports that you import but never actually use. The name comes from the idea of shaking a tree to remove dead leaves—your bundler "shakes" your dependency tree to drop dead code.

When you import a library, you might only use one or two functions from it. Without tree shaking, you'd ship the entire library to users. With tree shaking, only the code you actually call makes it into the final bundle.

How It Works

Bundlers rely on static analysis of ES6 module syntax (import and export). Because these statements are static (they must appear at the top level), bundlers can trace which exports are imported and which are actually invoked.

If you write:

import { formatDate, formatCurrency } from './utils.js';

console.log(formatDate(new Date()));
// formatCurrency is imported but never used

The bundler sees that formatCurrency is never called in your code. During the production build, it strips formatCurrency and any code it depends on from the final bundle.

Why It Matters

Tree shaking dramatically reduces bundle sizes, especially when using large libraries. You get the convenience of importing from comprehensive packages without the performance penalty of shipping unused code to users.

Key Takeaway: Tree shaking uses static analysis of ES6 modules to automatically eliminate unused exports, keeping your production bundles small and your applications fast.