Why Bundle Size Matters
Every kilobyte of JavaScript affects load time, parse time, and execution time. On mobile devices and slow networks, this impact is magnified.
Analyzing Bundle Size
Webpack Bundle Analyzer
// webpack.config.js
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin()
]
};Source Map Explorer
npx source-map-explorer dist/main.jsCode Splitting
Route-Based Splitting
// React with lazy loading
const Dashboard = React.lazy(() => import('./pages/Dashboard'));
const Settings = React.lazy(() => import('./pages/Settings'));
function App() {
return (
<Suspense fallback={<Loading />}>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
);
}Component-Level Splitting
// Load heavy components on demand
const HeavyChart = React.lazy(() => import('./HeavyChart'));
function Dashboard() {
const [showChart, setShowChart] = useState(false);
return (
<div>
<button onClick={() => setShowChart(true)}>Show Chart</button>
{showChart && (
<Suspense fallback={<Spinner />}>
<HeavyChart />
</Suspense>
)}
</div>
);
}Tree Shaking
Import Optimization
// Bad: imports entire library
import _ from 'lodash';
_.debounce(fn, 300);
// Good: imports only what's needed
import debounce from 'lodash/debounce';
debounce(fn, 300);
// Best: use ES modules with tree shaking
import { debounce } from 'lodash-es';Webpack Configuration
// Enable tree shaking
module.exports = {
mode: 'production',
optimization: {
usedExports: true,
sideEffects: true
}
};Asset Optimization
Image Optimization
// Use modern formats
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Fallback">
</picture>Font Optimization
/* Subset fonts to only needed characters */
@font-face {
font-family: 'CustomFont';
src: url('font.woff2') format('woff2');
font-display: swap;
unicode-range: U+0000-00FF; /* Latin characters only */
}Performance Budgets
Lighthouse CI
// lighthouserc.js
module.exports = {
ci: {
assert: {
assertions: {
'total-byte-weight': ['error', { maxNumericValue: 500000 }],
'first-contentful-paint': ['warn', { maxNumericValue: 2000 }],
'interactive': ['error', { maxNumericValue: 5000 }]
}
}
}
};Webpack Performance Hints
module.exports = {
performance: {
maxEntrypointSize: 250000,
maxAssetSize: 100000,
hints: 'error'
}
};Monitoring
- Track bundle size changes in CI/CD
- Monitor Real User Metrics (RUM)
- Set up alerts for performance regressions
Conclusion
Frontend performance is a feature. Implement performance budgets, monitor continuously, and make bundle size part of your code review process.