What is Tree-Shaking?
TL;DR
Build optimization that removes unused code from production bundles, reducing JavaScript bundle sizes.
Tree-Shaking is an automatic build optimization that eliminates unused code (dead code) from your production JavaScript bundles. Next.js and its bundler (Turbopack/Webpack) analyze your imports and only include the code that's actually used.
How tree-shaking works:
// utils.ts
export const usedFunction = () => 'used';
export const unusedFunction = () => 'never called';
// page.tsx
import { usedFunction } from './utils';
// Result: Only usedFunction is included in the bundle, unusedFunction is removed.
Optimizing for Tree-Shaking:
1. Use ES modules (import/export):
// Good - tree-shakeable
import { Button } from '@/components/ui/button';
// Bad - not tree-shakeable
const Button = require('@/components/ui/button');
2. Import only what you need:
// Good
import { map } from 'lodash-es';
// Bad
import _ from 'lodash';
3. Use side-effect-free code:
Functions without side effects are easier to shake.
Key benefits:
- Smaller bundles: Only ship code that's actually used
- Faster load times: Less JavaScript to download and parse
- Better performance: Reduced parse and execution time
- Automatic optimization: No manual configuration needed
AI-Friendly: ES Module syntax (import/export) provides clear dependency graphs. AI tools can analyze imports, identify unused exports, suggest refactoring opportunities, and recommend more tree-shake-friendly import patterns.