Analyze and Reduce Bundle Size
Intermediate12 min
Visualize your JavaScript bundle, identify bloated dependencies, and apply tree-shaking and code-splitting to reduce load times.
Prerequisites
- -React or Next.js project
- -Production build capability
Steps
1
Install the bundle analyzer
Add @next/bundle-analyzer for Next.js or webpack-bundle-analyzer for other setups.
$ pnpm add -D @next/bundle-analyzer
2
Configure the analyzer in next.config
Wrap your Next.js config with the bundle analyzer plugin.
$ echo "const withBundleAnalyzer = require('@next/bundle-analyzer')({ enabled: process.env.ANALYZE === 'true' });\nmodule.exports = withBundleAnalyzer(nextConfig);"
For non-Next.js projects, use 'npx vite-bundle-visualizer' or 'npx webpack-bundle-analyzer stats.json'.
3
Generate the bundle analysis report
Build with the ANALYZE flag to open an interactive treemap in the browser.
$ ANALYZE=true pnpm build
4
Check individual package sizes with bundlephobia
Quickly check the cost of any npm package before adding it.
$ npx bundle-phobia-cli lodash dayjs date-fns
Prefer smaller alternatives: dayjs over moment, zustand over redux, preact/signals over mobx.
5
Apply dynamic imports for code splitting
Lazy-load heavy components to reduce the initial bundle size.
$ echo "const HeavyChart = dynamic(() => import('./HeavyChart'), { loading: () => <Skeleton />, ssr: false });"
Full Script
FAQ
Discussion
Loading comments...