Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add craco webpack plugin by condition for create react app

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)
like image 625
Tuz Avatar asked Feb 13 '26 22:02

Tuz


2 Answers

You can set an environment variable right before any script command. For example, in your package.json, add a new line in the scripts paragraph that sets some variables:

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

In craco.config.js you can simply use:

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

Now, running npm run analyzer will both, set node env to production, set a variable ANALYZER to test (used later on) and load the craco config, that will start both the webpack server and the analyser.

like image 135
Nicolae Lozovan Avatar answered Feb 15 '26 11:02

Nicolae Lozovan


you can use conditions from craco like when, whenDev, whenProd, whenTest

 webpack: {
    plugins: [...whenDev(() => [new BundleAnalyzerPlugin()], [])]
},
like image 34
Farid Mammadov Avatar answered Feb 15 '26 12:02

Farid Mammadov