Environment-specific config in React
If we want to have different settings based on the environment (development, test, production) we can leverage environment variables. However, if we bootstrapped our React application using "Create-react-app" command, we don't have access to the Webpack for the fully customised build. Instead, we can define variables in our NPM scripts and in our code we can test those variables and implement different functionalities.
For example in our package.json
file we can have something like this:
"scripts": {
"build": "cross-env REACT_APP_AGE=30 react-scripts build"
},
And in our code we can retrieve the value like this:
const { REACT_APP_AGE } = process.env;
Please note that the variable name should start with REACT_APP_
otherwise React doesn't import the variable.
There is a special variable named NODE_ENV
which react automatically set value for. NODE_ENV
is set to development
when we run npm start
or npm test
and it's set to production
when we use npm run build
.