how to use .env.qa or .env.staging with create react app

14.3k Views Asked by At

The CreateReactApp documentation shows that you can use a limited number of .env files. https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env

I want to use more .env files for other environments, but .env.development is always used.

How can I use other files? I've found this article but it is not working for me. https://medium.com/@tacomanator/environments-with-create-react-app-7b645312c09d

I'm using react-scripts v3.4.1

2

There are 2 best solutions below

0
cyrf On

Well, the article is actually right. I had a bug in my code, where I had hard-coded the value rather than relying on process.env.REACT_APP_SOMEVAR

These scripts in package.json work fine:

"start": "REACT_APP_ENV=dev npm run start-env",
"start-env": "sh -ac '. .env.${REACT_APP_ENV}; react-scripts start'",
"start-dev": "REACT_APP_ENV=dev npm run start-env",
"start-qa": "REACT_APP_ENV=qa npm run start-env",
"build": "REACT_APP_ENV=dev npm run build-env",
"build-env": "sh -ac '. .env.${REACT_APP_ENV}; react-scripts build'",
"build-dev": "REACT_APP_ENV=dev npm run build-env",
"build-qa": "REACT_APP_ENV=qa npm run build-env",
1
qslabs On

create-react-app officially addresses this desire here.

They advise creating your custom .env then loading it using npm package env-cmd in a custom build script.

So, from their documentation:

{
  "scripts": {
    "build:staging": "env-cmd -f .env.staging npm run build"
  }
}