Environment Variables in React

From Logic Wiki
Jump to: navigation, search


in the root of the project create a file with no name but env extension

.env

for environment specific files it will be

.env.development

it should contain key value pairs and keys must start with REACT_APP_ so it should look like this

REACT_APP_NAME=My First App
REACT_APP_VERSION=1.0.0
REACT_APP_STAGE="dev"

React Sample Config file for Different Environment

To read this

console.log(process.env.REACT_APP_NAME);

Variables can be set in terminal or in env files

Environment variables extracted and replaced in the code during build.

to build with optimised code

 npm run build

this creates a folder named build

Alternative builds in package.json

 "scripts": {
    "start": "\"set REACT_APP_ENV=local & react-scripts start\" - uses .env",
    "build": "\"set REACT_APP_ENV=local & react-scripts build\" - uses .env",
    "build-dev": "\"set REACT_APP_ENV=dev & react-scripts build\" - uses .env.dev",
    "build-systest": "\"set REACT_APP_ENV=systest & react-scripts build\" - uses .env.systest",
    "build-uat": "\"set REACT_APP_ENV=uat & react-scripts build\" - uses .env.uat",
    "build-production": "\"set REACT_APP_ENV=production & react-scripts build\" - uses .env.production",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "postbuild": "node iisConfig/copyIISConfig.js"
  },

and to run this optimised code in the machine install serve first if it's not already installed

npm i -g serve

and run this

serve -s build 

so for production environment npm run build and it looks for the environment env.production

for test npm test and it looks for env.test