JavaScript PerformanceLesson 4.5
How to use a bundle analyzer to find and remove large dependencies
webpack-bundle-analyzer, rollup-plugin-visualizer, vite-bundle-visualizer, finding large modules, replacing heavy libraries, moment.js vs day.js, lodash vs lodash-es, cherry-picking imports
Analyzing and Reducing Bundle Size
A bundle analyzer renders your JavaScript output as a treemap - each rectangle is a module, sized by its contribution to the bundle. It's the fastest way to find which dependencies are costing the most.
# Vite - generates stats.html in dist/
npm install --save-dev rollup-plugin-visualizer
# vite.config.js
import { visualizer } from 'rollup-plugin-visualizer';
export default {
plugins: [visualizer({ open: true })]
};# Webpack
npm install --save-dev webpack-bundle-analyzer
npx webpack --profile --json > stats.json
npx webpack-bundle-analyzer stats.jsonCommon large dependencies and their replacements:
- moment.js (67KB) → day.js (2KB) - identical API for 90% of use cases
- lodash (71KB) → lodash-es + tree shaking - import only what you use
- date-fns (full) → named imports from date-fns - already ESM, just use named imports
// 71KB - entire lodash
import _ from 'lodash';
// ~1KB - only debounce
import debounce from 'lodash-es/debounce';
// 67KB - moment
import moment from 'moment';
// 2KB - day.js, same API
import dayjs from 'dayjs';Before installing any replacement, check Bundlephobia for gzipped size - it's the fastest way to compare candidates without leaving the browser.
