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';After identifying a large module, check its npm page and README for an ESM or lighter alternative. Bundlephobia shows the gzipped size of any npm package before you install it.
