0

I have a react app with build folder ( generated by : npm run build ) , I want to have 3 variables in my .env file ( just one file ):

REACT_APP_API_URL=http://localhost:3000/api ( for production)
REACT_APP_PROD_URL=http://localhost:3001/api ( for staging)
REACT_APP_STAGIN_URL=http://localhost:3002/api ( for development)

and use them in the npm run build folder

Ahmed Derbel
  • 37
  • 2
  • 8

3 Answers3

8
  • Create differences env files
  • install yarn add env-cmd
  • and add script to package.json:

"start-qa": "env-cmd -f .env.qa react-scripts start"

or build:

"build-qa": "env-cmd -f .env.qa react-scripts build"

Idan
  • 3,604
  • 1
  • 28
  • 33
3

try with cross-env

something like this in your package.json

"start":  cross-env REACT_APP_API_URL=http://localhost:3000/api node scripts/start.js

may be it will help you in achieving your stuff

komal deep singh chahal
  • 1,229
  • 3
  • 13
  • 28
1

You need to create a separate .env file for each environment.

As said in CRA Documentation: What other .env files can be used?:

.env.development, .env.test, .env.production: Environment-specific settings.

You can't place all your env variables in one file, the values will be overridden. For more information check dotenv documentation

Or if you want to edit env variables after building your project, please refer to this: https://stackoverflow.com/a/56120507/5078746

Fcmam5
  • 4,888
  • 1
  • 16
  • 33
  • I can't have 3 var and each variables has it's own name ? and I test if node_env==prod I call the production url .. ? – Ahmed Derbel Jul 20 '20 at 12:24
  • You can't do it in the same file, it will be overridden at it will take the last value for that variable. You either go for the suggested solution by having multiple `.env` files or create a file where you read your variables and apply your logic (`node_env==prod`...) – Fcmam5 Jul 20 '20 at 12:27