Course contentsShow
← React
Lesson 1419 of 2,39635. Code SplittingFree lesson

Tree-Shaking Failures and How to Fix Them

Identify when libraries aren't tree-shaking properly and how named imports vs default imports affect bundle size.

Tree-Shaking Failures and How to Fix Them

You'll learn how to spot when libraries aren't tree-shaking properly and fix it by changing your import style.

Tree-shaking is your bundler's ability to remove unused code from libraries. But sometimes it fails, and you import an entire library when you only need one function—bloating your bundle unnecessarily.

Why Tree-Shaking Fails

Default imports break tree-shaking. When you write:

import lodash from 'lodash';
const result = lodash.debounce(fn, 300);

Your bundler includes all of lodash (~70KB), even though you only use debounce. The default import prevents the bundler from knowing what's unused.

Named imports enable tree-shaking:

import { debounce } from 'lodash-es';

Now only debounce is bundled—massive savings! Note: lodash-es is the ES module version; regular lodash doesn't tree-shake well.

The Import Style Analogy

Think of default imports like ordering a combo meal—you get everything whether you want it or not. Named imports are à la carte: you specify exactly what you need and pay (in bytes) only for that.

Spotting the Problem in Bundle Analysis

When analyzing your bundle, if you see a library taking up hundreds of KBs but you only use a few functions, check your import style. Libraries like Moment.js, entire icon packs, or utility libraries are common culprits.

The Fix

  1. Use named imports when possible
  2. Choose ES module versions of libraries (lodash-es vs lodash)
  3. Some libraries offer subpath imports: import debounce from 'lodash/debounce'
  4. Replace non-tree-shakable libraries with modern alternatives (e.g., date-fns instead of Moment.js)

Key Takeaway: Use named imports from ES module libraries to enable tree-shaking; default imports often bundle entire libraries unnecessarily.