Bundle Optimization: Tree Shaking & Code Splitting
Bundle optimization minimizes JavaScript payload sizes through dead code elimination (Tree Shaking), dynamic route/component chunking (Code Splitting), and ES module analysis.
Why it matters in interviews
Visual & Interactive Explanation
1. Static ESM Analysis
Bundler inspects import/export statements across dependency graph
2. Dead Code Elimination (Tree Shaking)
Discards unreferenced functions and unused library modules
3. Dynamic Import Chunking
Splits modals, charts, and heavy tools into separate async .js chunks
4. Minification & Mangling
Terser/SWC compresses variable names and strips comments
5. Compression & CDN Delivery
Brotli / Gzip compression served from Edge CDN with immutable cache headers
Code Examples & Implementation
import dynamic from 'next/dynamic';
// Heavy 500KB chart library is NOT in initial page bundle!
// It is downloaded ONLY when the user clicks 'View Analytics'
const HeavyAnalyticsChart = dynamic(
() => import('@/components/HeavyAnalyticsChart'),
{
loading: () => <div className="h-64 animate-pulse bg-ink-panel rounded-lg" />,
ssr: false, // Don't even render canvas on server
}
);
export function Dashboard() {
const [showChart, setShowChart] = useState(false);
return (
<div>
<button onClick={() => setShowChart(true)}>View Analytics</button>
{showChart && <HeavyAnalyticsChart />}
</div>
);
}Interview-Ready Answers
Tree shaking removes unused exported code during build time using static ESM analysis. Code splitting breaks a monolithic bundle into smaller chunks loaded on demand when the user visits a route or opens a modal.
Official Documentation & Specifications
Follow-up Questions & Deep Dives
Common Mistakes & Anti-Patterns
- Importing an entire library like `import _ from 'lodash'` instead of `import debounce from 'lodash/debounce'`
- Using CommonJS `require()` in modern codebases, breaking tree shaking
- Eagerly loading massive PDF generators or rich text editors on initial page load
Real-World Architectural Scenario
Your initial JS bundle size is 1.4MB and initial page load on mobile 4G takes 5.2 seconds. How do you systematically bring it under 150KB?
Rate Your Readiness
Rate how comfortably you can explain this in an interview to update your global readiness gauge: