Rambo check
Rambo check

Reputation: 33

How to setup the env variable for the react app?

My react app is running on http://localhost:3000 and I wanted to setup the env variable for the different environment development, production, staging and local.

my react app url for different environment are(I am mocking my urls)

local = http://localhost:3000
development = http://react.developmet.com
production = http://react.production.com
stage = http://react.stage.com

looking for a solution how i can setup the env var for different environment.

Adding my approach to the same thing just wanted to know is this approach is good or not.

and how I can achieve same for staging environment

I have created an environment.js file.

let BASE_URL = http://localhost:3000

//check for environment
if (process.env.REACT_APP_ENV = "development") {
  BASE_URL = "http://react.developmet.com"
}
if (process.env.REACT_APP_ENV = "production") {
  BASE_URL = "http://react.production.com"
}

export {BASE_URL}

and also updated my run scripts

"scripts": {
     "dev":"REACT_APP_ENV=development npm start",
     "prod":"REACT_APP_ENV=productionnpm start",
     "build:dev":"REACT_APP_ENV=development npm run-script build",
     "build:prod":"REACT_APP_ENV=production npm run-script build",
    }

Upvotes: 1

Views: 8391

Answers (1)

Ajeet Shah
Ajeet Shah

Reputation: 19813

You can use env-cmd to manage your build for multiple env files:

Installation:

yarn add env-cmd -D

Create env files

  1. Create a folder envs at root project level
  2. Create .env files (as many as you need)

e.g. envs/.env.dev, envs/.env.prod, envs/.env.staging etc

A Sample .env (e.g. envs/.env.prod) file

REACT_APP_API_HOST=http://my-prod-api.example.com
REACT_APP_ANY_OTHER_VAR=some_value

Configure scripts in package.json file:

"scripts": {
    "start": "react-scripts start",
    "eject": "react-scripts eject",
    "dev": "env-cmd -f envs/.env.dev react-scripts build",
    "prod": "env-cmd -f envs/.env.prod react-scripts build",
    "staging": "env-cmd -f envs/.env.staging react-scripts build",
  },

Make the build:

$ yarn dev // to make build for dev env
$ yarn prod // to make build for prod env
$ yarn staging // to make build for staging env

PS: You can use npm commands as well. I used yarn only for example purpose.

Upvotes: 4

Related Questions