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.

Last updated: November 25, 2025

Ready to Launch Your SaaS Faster?

Start from a stable architecture that makes AI more reliable, not confused — so you can go from idea to product in record time.

AI-friendly architecture
Production ready from day one
Lifetime updates