Home Navigation

Monday 25 November 2019

React manage different environment variable with .env file



React web application has two values environment variable NODE_ENV, it is either production or development. You can not modify the variable NODE_ENV, this is an international setting to protect the production environment from an accidental development.

  "scripts": {
    "start": "react-scripts start", // the value of NODE_ENV is development
    "build": "react-scripts build", // the value of NODE_ENV is production
...
}


.env: Default.
.env.local: Local overrides. This file is loaded for all environments except test.
.env.development, .env.test, .env.staging, .env.production: Environment-specific settings.
.env.development.local, .env.test.local, .env.production.local: Local overrides of environment-specific settings.

.env file will be use used for runing by defualt
.env.development file will be used for running script npm start
.env.production file will be used for running script npm build

To create different environmental variable and use them in react code create the below files in the root directory of the project

filename: .env
contents:  REACT_APP_PAGE_TITLE = "My React app application"

filename: .env.development
contents:  REACT_APP_MY_API = "https://development-my-api.com/"
  REACT_APP_ENV=dev

filename: .env.staging
contents:  REACT_APP_MY_API = "https://staging-my-api.com/"
  REACT_APP_ENV=staging

filename: .env.production
contents:  REACT_APP_MY_API = "https://prod-my-api.com/"
  REACT_APP_ENV=prod

install the below package:

$ npm install env-cmd --save
or
$ yarn add env-cmd


Modify script in package.json and it should be look like below

"scripts": {
    "start": "react-scripts start", // the value of NODE_ENV is development
    "build": "react-scripts build", // the value of NODE_ENV is production
"build:staging": "env-cmd -f .env.staging react-scripts build", // the value of NODE_ENV is still production
...
}

To test the application if it works, add the below tags in your app.js

<div>
      <h1>{process.env.REACT_APP_PAGE_TITLE}</h1> 
      <small>You are running this application in <b>{process.env.REACT_APP_ENV}</b> mode.</small>
      <p>{process.env.REACT_APP_MY_API}</p>
  </div>


Run application
development:
npm start


Staging:
npm run build:staging // build the application for staging
serve -s build // run the application compiled for staging


production:
npm run build // build the application for production
serve -s build // run the application compiled for production


No comments:

Post a Comment