Shrinking Your Bundle
Find what's bloating your JavaScript and fix it in 30 minutes.
TL;DR
Run ANALYZE=true npm run build to find bloat. Replace moment with date-fns, use direct lodash imports, fix barrel file imports. Use modularizeImports for automatic tree-shaking.
A bloated bundle costs you twice: slow page loads AND higher bandwidth bills.
Setup (2 minutes)
npm install @next/bundle-analyzerconst withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withBundleAnalyzer({
// your existing config
});ANALYZE=true npm run buildOpens an interactive treemap. Bigger rectangles = bigger problems.
The Usual Suspects
| Library | Size | Replace With |
|---|---|---|
moment | 300KB | date-fns (20KB) |
lodash (full) | 70KB | Direct imports |
| Icon libraries | 100KB+ | Direct imports or @iconify/react |
@aws-sdk/* | 500KB+ | Should be server-only |
chart.js | 200KB | Lazy load it |
Quick Fixes
Moment → date-fns
// Before
import moment from 'moment';
moment(date).format('YYYY-MM-DD');
// After
import { format } from 'date-fns';
format(date, 'yyyy-MM-dd');Lodash Direct Imports
// Before: pulls in everything
import _ from 'lodash';
_.debounce(fn, 300);
// After: just what you need
import debounce from 'lodash/debounce';
debounce(fn, 300);Icon Library Fixes
// Before: may import all icons
import { FaHome } from 'react-icons/fa';
// After: specific import path
import { FaHome } from 'react-icons/fa6';Auto-Fix with modularizeImports
Force proper tree-shaking for problem packages:
module.exports = {
modularizeImports: {
'lodash': {
transform: 'lodash/{{member}}',
},
'@mui/icons-material': {
transform: '@mui/icons-material/{{member}}',
},
'@heroicons/react/24/outline': {
transform: '@heroicons/react/24/outline/{{member}}',
},
},
};Now import { debounce } from 'lodash' automatically becomes import debounce from 'lodash/debounce'.
The Barrel File Problem
export * from './Button';
export * from './Modal';
export * from './Chart'; // 200KB!// Importing one thing evaluates everything
import { Button } from '@/components'; // Pulls in Chart tooFix: Import from source files directly:
import { Button } from '@/components/Button';Key Takeaways
Check package sizes No single package should exceed 100KB without justification.
Verify server-only code stays server-side AWS SDK, database drivers, etc. should never appear in client bundles.
Eliminate duplicates Watch for the same package appearing multiple times with different versions.
Verify tree-shaking Icon libraries and lodash should only include what you actually use.
Next: Dynamic Imports - load heavy code only when needed.