Tree Shaking
What is Tree Shaking?
Tree shaking is a dead code elimination technique that removes unused exports from JavaScript bundles. It relies on ES Modules' static structure to determine what code is actually used.
Key Concept: Tree shaking works because ES Modules use static imports (analyzed at compile time) vs CommonJS's dynamic requires (evaluated at runtime).
1. Tree Shaking Friendly Code
JavaScript Editor
Best Practices:
- Use named exports for individual functions
- Avoid default exporting large objects
- Keep modules focused and small
3. Side Effects Configuration
JavaScript Editor
Properly configuring side effects is crucial for effective tree shaking.
2. Tree Shaking Anti-patterns
JavaScript Editor
Avoid these patterns:
- Dynamic property access on module exports
- Side effects at module level
- Wildcard re-exports (
export *)
4. Real-world Example
JavaScript Editor
Tree shaking can dramatically reduce bundle sizes in utility libraries.
5. Testing & Verification
JavaScript Editor
Tools for Bundle Analysis:
- webpack-bundle-analyzer: Visualize bundle contents
- source-map-explorer: Analyze bundle size contributions
- rollup-plugin-visualizer: Rollup bundle visualization
- Bundlephobia: Check npm package sizes
Tree Shaking Checklist
| Do | Don't |
|---|---|
| ✅ Use ES Modules (import/export) | ❌ Use CommonJS (require/module.exports) |
| ✅ Export functions individually | ❌ Export large objects/classes as default |
| ✅ Mark side effects in package.json | ❌ Have side effects at module level |
| ✅ Use pure annotations for expensive calls | ❌ Use dynamic property access on exports |
| ✅ Test with production builds | ❌ Assume tree shaking works without verification |