Introduction
JavaScript is the most expensive resource on the web — it must be downloaded, parsed, compiled, and executed. Every kilobyte matters, especially on mobile devices with slower CPUs.
Bundle size optimization is about shipping only the code users need, when they need it. This involves tree shaking dead code, splitting bundles by route, and choosing lighter alternatives.
This guide covers practical techniques to analyze, reduce, and maintain small JavaScript bundles.
Key Concepts
Tree Shaking
// ❌ No tree shaking
import _ from 'lodash';
// ✅ Tree-shakeable
import { get } from 'lodash-es';
Code Splitting
// vite.config.ts
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
charts: ['recharts', 'd3'],
}
}
}
}
});
Bundle Analysis
# Vite
npx vite-bundle-visualizer
# webpack
npx webpack-bundle-analyzer stats.json
# Quick size check
npx bundlephobia lodash
Practical Examples
1. Replace Heavy Libraries
// ❌ moment.js — 67KB gzipped
import moment from 'moment';
// ✅ date-fns — 2KB per function
import { format } from 'date-fns';
// ✅ Native Intl API — 0KB
new Intl.DateTimeFormat('en').format(new Date());
2. Dynamic Import for Heavy Features
async function openEditor() {
const { EditorComponent } = await import('./rich-editor');
renderEditor(EditorComponent);
}
3. Next.js Optimization
// next.config.js
module.exports = {
experimental: {
optimizePackageImports: ['@heroicons/react', 'lucide-react'],
},
};
Best Practices
- ✅ Regularly analyze your bundle with visualization tools
- ✅ Use ES module versions of libraries for tree shaking
- ✅ Set a bundle budget (e.g., <150KB gzipped for initial JS)
- ✅ Dynamic import heavy libraries used on specific pages only
- ✅ Check package size before installing with bundlephobia.com
- ❌ Don't import entire icon libraries — import individual icons
Common Pitfalls
- 🚫 Barrel file imports without tree shaking — may pull everything
- 🚫 Not checking transitive dependencies
- 🚫 Over-splitting — too many tiny chunks cause network waterfall
- 🚫 Ignoring polyfills — target only browsers you support
Related Guides
- → Lazy Loading Patterns
- → Prefetching & Preloading
- → Performance Monitoring Setup