Course contentsShow
← JavaScript
Lesson 2466 of 2,72350. JavaScript Build ToolingFree lesson

What is Tree Shaking?

Understanding how tree shaking eliminates unused code from your final bundle to reduce file size.

What is Tree Shaking?

You'll learn how build tools automatically eliminate unused code from your JavaScript bundle to keep file sizes lean.

The Core Idea

Tree shaking is a dead code elimination technique that removes exports you've defined but never actually import or use anywhere in your application. The name comes from the idea of shaking a tree to make dead leaves fall off—your bundler "shakes" your dependency tree and lets unused code drop away.

When you import from a module, you might only use a fraction of what it exports. Without tree shaking, your bundle would include everything that module offers. Tree shaking analyzes your code's static structure (which imports are actually referenced) and strips out the rest before producing your final bundle.

How It Works

Tree shaking relies on ES modules' static import/export syntax. Because import and export statements are analyzed at compile time (not runtime), bundlers can trace exactly which exports are used across your entire codebase. If you export ten functions but only import two, the other eight won't appear in your production bundle.

This is why ES modules are preferred over CommonJS (require) for modern bundling—require is dynamic and can't be analyzed as reliably.

Why It Matters

For large applications and dependencies, unused code can bloat your bundle by hundreds of kilobytes or more. Tree shaking keeps your bundles lean, which means faster downloads, parsing, and execution in the browser. It's especially powerful with utility libraries—you might import one function from a massive library without paying the cost of shipping the entire thing.

Key Takeaway: Tree shaking uses static analysis of ES module imports/exports to automatically remove unused code from your final bundle, dramatically reducing file size without manual intervention.