如何传递 cli 参数来反应 craco?

How to pass cli arguments to react craco?

我想在我的 React 应用程序中添加一个 bundle-analyzer,当开发人员运行 yarn analyze 时,它已在 package.json 中设置为 "analyze": "craco build --analyze-only"

我确实阅读了 craco 的手册,但没有找到任何解决方案。我当前的配置如下:

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;
    }
  }
};

我们如何将参数传递给它?

您可以使用process.argv来检查参数,例如:

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

      return webpackConfig;
    }
  }
};