Setting Up webpack-bundle-analyzer
You'll learn how to install and configure webpack-bundle-analyzer to visualize your React app's bundle composition.
Now that you understand why bundle size matters and how to read bundle reports, let's actually set up the tool that generates those visualizations.
What webpack-bundle-analyzer Does
Think of it as an X-ray machine for your JavaScript bundles. It creates an interactive treemap showing every module, library, and component—sized proportionally to how much space it takes up. You can instantly spot bloated dependencies or accidentally imported libraries.
Installation
First, install the package as a dev dependency:
npm install --save-dev webpack-bundle-analyzer
For Create React App (CRA)
CRA hides webpack configuration by default. You have two options:
Option 1: Temporary analysis without ejecting
npx cra-bundle-analyzer
This runs your production build and opens the visualization automatically.
Option 2: After ejecting (if you've run npm run eject):
In config/webpack.config.js, add:
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// In the plugins array:
plugins: [
// ... other plugins
new BundleAnalyzerPlugin()
]
For Custom Webpack Setups
Add directly to your webpack configuration:
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = {
// ... your config
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static', // generates HTML file
openAnalyzer: false // won't auto-open browser
})
]
};
Run your production build, and you'll see a colorful interactive report showing exactly what's in your bundle.
Key Takeaway: webpack-bundle-analyzer is installed as a dev dependency and integrates either through helper tools (CRA) or directly in webpack config (custom setups), generating visual reports that reveal your bundle's composition.