Frontend Patterns

Pattern

Tree Shaking

Eliminate unused code from bundles during the build process.

Performance Advanced

Tree Shaking

Problem

Bundles include entire libraries even when only one function is used. Importing a single utility from lodash ships the entire 70KB library. Dead code from refactored features remains in production bundles indefinitely. Users download and parse thousands of unused functions on every page load.

Solution

Eliminate unused code during bundling by analyzing import graphs and removing dead exports. This reduces bundle size by including only what’s actually used.

Example

This demonstrates using named imports to enable tree-shaking, which eliminates unused code from bundles during the build process, dramatically reducing bundle sizes.

// Use named imports for tree-shaking - only imports what's used
import { Button, Input } from 'my-library'; // Only Button and Input bundled

// Avoid default imports of entire libraries
// import _ from 'lodash'; // BAD - bundles entire 70KB library
import { debounce } from 'lodash-es'; // GOOD - only bundles debounce function

Benefits

  • Dramatically reduces bundle size by removing unused code.
  • Improves load times and parsing performance.
  • Happens automatically during build without runtime overhead.
  • Particularly effective with large libraries where only parts are used.

Tradeoffs

  • Requires ES modules and proper build configuration to work effectively.
  • Can fail if code uses dynamic imports or non-static analysis patterns.
  • Debugging is harder when trying to understand what was removed.
  • May not work with CommonJS modules or poorly structured packages.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.