Tree Shaking and Named Exports
What you'll learn: How named exports enable bundlers to eliminate unused code more effectively than default exports.
What Is Tree Shaking?
Tree shaking is a technique used by module bundlers (like Webpack or Rollup) to remove unused code from your final JavaScript bundle. Think of it like shaking a tree to make dead leaves fall off — the bundler "shakes" your dependency tree to drop code you never actually use.
Why Named Exports Are Better for Tree Shaking
Named exports make dependencies explicit and granular. When you import specific named exports, the bundler can clearly see exactly which parts of a module you're using:
// utils.js
export function formatDate(date) { /* ... */ }
export function parseJSON(str) { /* ... */ }
export function debounce(fn, ms) { /* ... */ }
// app.js
import { formatDate } from './utils.js';
// Only formatDate is used
// Bundler can safely remove parseJSON and debounce
The bundler analyzes your import statement and knows you only need formatDate. The other two functions can be safely excluded from the final bundle.
The Problem with Default Exports
Default exports are imported as single objects, making it harder for bundlers to determine what's actually used:
// utils.js
export default {
formatDate() { /* ... */ },
parseJSON() { /* ... */ },
debounce() { /* ... */ }
};
// app.js
import utils from './utils.js';
utils.formatDate(new Date());
// Bundler sees the whole 'utils' object imported
// Harder to determine which methods are truly needed
The bundler sees you imported the entire object and must be conservative about what to remove.
Key Takeaway: Named exports create explicit, traceable dependencies that allow bundlers to confidently remove unused code, resulting in smaller, faster production bundles — a significant advantage over default exports for library and utility modules.