Search code examples
reactjswebpackcreate-react-appcraco

How to pass cli arguments to react craco?


I want to add a bundle-analyzer to my react app, when the developer runs yarn analyze which has been set in package.json as "analyze": "craco build --analyze-only".

I did read the craco's manual but didnt find any solution for this. my current config is as below:

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

module.exports = {
  reactScriptsVersion: 'react-scripts' /* (default value) */,
  webpack: {
    alias: {},
    plugins: {
      add: [progressBar()] /* An array of plugins */
    },
    configure: (webpackConfig, { env, paths }) => {
      if (env === 'production') {
        webpackConfig.plugins.push(new BundleAnalyzerPlugin());
      }
      return webpackConfig;
    }
  }
};

How can we pass the args to it?


Solution

  • You can use process.argv to check the arguments, e.g:

    // craco.config.js
    //...
    module.exports = {
      // ...
      webpack: {
      //...
        configure: (webpackConfig, { env, paths }) => {
          if (process.argv.includes('--analyze-only'))
            webpackConfig.plugins.push(new BundleAnalyzerPlugin());
    
          return webpackConfig;
        }
      }
    };