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)
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.
you can use conditions from craco like when, whenDev, whenProd, whenTest
webpack: {
plugins: [...whenDev(() => [new BundleAnalyzerPlugin()], [])]
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With