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

Writing Tree-Shakeable Code

Using named exports and avoiding side effects to enable effective tree shaking.

Writing Tree-Shakeable Code

You'll learn how to structure your JavaScript modules so bundlers can effectively remove unused code through tree shaking.

The Core Principle

Tree shaking only works if your bundler can confidently identify which code is unused. This means writing code that's statically analyzable—where imports and exports can be determined at build time, not runtime. Two practices make this possible: using named exports and avoiding side effects.

Use Named Exports

Named exports allow bundlers to track exactly which pieces of a module are imported:

// ✅ Tree-shakeable: each function is a separate named export
export function calculateTax(price) {
  return price * 0.1;
}

export function formatCurrency(amount) {
  return `$${amount.toFixed(2)}`;
}

// ❌ Not tree-shakeable: default export of an object
export default {
  calculateTax: (price) => price * 0.1,
  formatCurrency: (amount) => `$${amount.toFixed(2)}`
};

When you import just calculateTax, the bundler can remove formatCurrency from the first example but must include the entire object in the second.

Avoid Side Effects

Side effects—code that runs just by importing a module—prevent tree shaking. Bundlers can't safely remove code if it might be doing something important:

// ❌ Has side effects: runs code on import
console.log('Utils loaded!');

export function add(a, b) {
  return a + b;
}

// ✅ No side effects: pure exports only
export function add(a, b) {
  return a + b;
}

Think of it this way: Named exports are like individual items on a store shelf—you can pick what you need. Default object exports are like pre-packaged bundles—take everything or nothing.

Key Takeaway: Write tree-shakeable code by using named exports for each function/constant and keeping your modules free of side effects—this lets bundlers surgically remove unused code.