debugjavascriptwebpackMajorpending
Debug: Webpack bundle too large
Viewed 0 times
bundle-sizeanalyzercode-splittingtree-shakinglazy-loading
Error Messages
Problem
Production JavaScript bundle is too large, causing slow page loads. Need to identify and reduce bundle bloat.
Solution
Step-by-step bundle analysis and reduction:
npm install --save-dev webpack-bundle-analyzer
# In webpack config:
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
plugins: [new BundleAnalyzerPlugin()]
# Or for Next.js:
npx @next/bundle-analyzer
a) moment.js (300KB) -> dayjs (2KB) or date-fns (tree-shakeable)
b) lodash (70KB) -> lodash-es (tree-shakeable) or native methods
c) Full icon libraries -> import specific icons
Bad: import { icons } from 'lucide-react'
Good: import { Search } from 'lucide-react'
// Dynamic imports
const Heavy = React.lazy(() => import('./HeavyComponent'));
// Route-based splitting (Next.js does this automatically)
- Use ES modules (import/export), not CommonJS (require)
- Set sideEffects: false in package.json
- Avoid barrel files (index.ts re-exporting everything)
npx webpack --stats | grep -i duplicate
# Or use duplicate-package-checker-webpack-plugin
- Analyze bundle contents:
npm install --save-dev webpack-bundle-analyzer
# In webpack config:
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
plugins: [new BundleAnalyzerPlugin()]
# Or for Next.js:
npx @next/bundle-analyzer
- Common culprits and fixes:
a) moment.js (300KB) -> dayjs (2KB) or date-fns (tree-shakeable)
b) lodash (70KB) -> lodash-es (tree-shakeable) or native methods
c) Full icon libraries -> import specific icons
Bad: import { icons } from 'lucide-react'
Good: import { Search } from 'lucide-react'
- Code splitting:
// Dynamic imports
const Heavy = React.lazy(() => import('./HeavyComponent'));
// Route-based splitting (Next.js does this automatically)
- Tree shaking prerequisites:
- Use ES modules (import/export), not CommonJS (require)
- Set sideEffects: false in package.json
- Avoid barrel files (index.ts re-exporting everything)
- Check for duplicates:
npx webpack --stats | grep -i duplicate
# Or use duplicate-package-checker-webpack-plugin
Revisions (0)
No revisions yet.