1

I am using craco with create react app and I would like to add a plugin only in DEV mode or by ENV Var

my craco.config looks is:

const path = require('path');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

module.exports = () => {
  return {
    webpack: {
      alias: {
        environment: path.join(
          __dirname,
          'src',
          'environments',
          process.env.CLIENT_ENV || 'production'
        )
      }
      //   plugins: [new BundleAnalyzerPlugin()]
    },
    jest: {
      configure: {
        testPathIgnorePatterns: ['<rootDir>/src/environments/'],
        moduleNameMapper: {
          environment: '<rootDir>/src/environments/test'
        }
      }
    }
  };
};

so I would like this BundleAnalyzerPlugin. only if the ENV param x =true or if NODE_ENV=test

while I trying to push to plugin array I got that plugin I undefined

module.exports.webpack.plugins.push(plugin)
4

2 回答 2

3

您可以在任何脚本命令之前设置环境变量。例如,在您的 package.json 中,在scripts设置一些变量的段落中添加一个新行:

 "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "analyzer": "env NODE_ENV=production ANALYZER=test yarn start"
 }

craco.config.js你可以简单地使用:

 plugins: process.env.ANALYZER === 'test' ? [new BundleAnalyzerPlugin()] : []

现在,运行npm run analyzer两者,将 node env 设置为production,将变量设置ANALYZERtest(稍后使用)并加载 craco 配置,这将启动 webpack 服务器和分析器。

于 2020-08-05T18:49:26.017 回答
0

您可以使用 craco 中的条件,例如when, whenDev, whenProd,whenTest

 webpack: {
    plugins: [...whenDev(() => [new BundleAnalyzerPlugin()], [])]
},
于 2022-01-31T09:13:05.660 回答