Search code examples
reactjswebpackwebpack-bundle-analyzer

How to configure webpack-bundle-analyzer for react?


I'm trying configure my webpack.config for webpack-bundle-analyzer. Here how it looks.

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin()
  ]
}

And it shows only index.js, main.js and src folders. How to see all my other dependencies?

enter image description here


Solution

  • First npm install --save-dev webpack-bundle-analyzer Second, add some config in webpack.config.js Here's my config when using create react app in config/webpack.config.js

    Import the library in the top

    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
    

    Add also some validation so your build script doesn't have a problem when you deploy to production

    const withReport = process.env.npm_config_withReport
    

    Add this code inside plugins

    plugins:[
      withReport ? new BundleAnalyzerPlugin() : '',
    ]
    

    lastly, add a new script inside package JSON

    "report": "npm run build --withReport true"
    

    Go run "npm run report" in your terminal. should be automatically appear the webpack bundle analyzer UI