My company uses the three standard environments: Development, Test, and Production. My create-react-app based application is hosted as a content item within our CMS, so to get it into any environment, I need to run the npm run build
command.
I've created a file, config.js, which exports a different configuration object based on variables in process.env
, but the default behavior here has the limitation that npm run build
is always considered production. This makes sense, I just need different behavior.
What I'd like to do is run a script like npm run build:dev
, etc, which sets a process.env variable that I can switch on. Essentially I need to create an npm script that sets a dotenv
variable, then calls npm run build
.
What is the best way to accomplish this?
You can use cross-env package (from npm) to define a environment variable.
Just install the package:
npm install --save-dev cross-env
And create your custom script hwere do you define your variable, for example:
{
"scripts": {
"build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
}
}
It worked like a charm on my projects.
More information here cross-env