'Using environment variable in React
I have a react application that is using node v12.19.0 and trying to create a profile for dev and test environment, so that application can be easily promoted to different envrionments. Below are the steps I tried to implement but getting error:
- Updated the package.json file with env-cmd for dev and test environments.
- Created env-cmdrc file to store environment variables for different environments.
- Like App.js I have my landing page called as GeneralRule.js where I am trying to print the environment variables. After making the above changes I tried to build the app but when i refresh on browser i get following error: Uncaught ReferenceError: process is not defined
Below are the code changes: Code changes in package.json
"scripts":{"test": "jest --notify --no-cache",
"start": "cross-env DEBUG=axios NODE_ENV=development nodemon --inspect server",
"start:test": "cross-env DEBUG=axios env-cmd -e test nodemon --inspect server",
"lint:css": "stylelint './src/**/*.js'",
"lint:eslint:fix": "eslint --ignore-path .gitignore --ignore-pattern internals/scripts --fix",
"lint:eslint": "eslint --ignore-path .gitignore --ignore-pattern internals/scripts || exit 0",
"lint:js": "npm run lint:eslint -- . || exit 0",
"lint:staged": "lint-staged",
"lint": " exit 0",
"debug": "node --inspect-brk jest --notify --no-cache",
"test:cover": "jest --notify --no-cache --coverage -u",
"build": "webpack --mode production"},
Code changes in env-cmdrc
{
"dev":{
"REACT_APP_VERSION": "call development create rule api"
},
"test":{
"REACT_APP_VERSION": "call test create rule api"
}
}
Code changes in GeneralRules.js like App.js
return (
<React.Fragment>
<p>{process.env.NODE_ENV}</p>
<p>{process.env.REACT_APP_VERSION}</p>
<h1 style={{ marginTop: "1em" }}>
General Rule ({rules.generalRules.length})
</h1>
------
------
</React.Fragment>
); };
Command to build the app:
npm run start:test
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

