简体   繁体   中英

Load different env variables with .env and create-react-app

I need to load for each development/production server a different .env file.

Dev/Prod Server     | .env file
---------------------------------------------
localhost           | .env.development.local
development         | .env.development
qa                  | .env.qa
production          | .env.production

So, I tried to edit the package.json in this way

"start-js": "react-scripts start .env.development.local",
"start": " npm-run-all -p watch-css start-js",
"build:dev": "npm run build-css && react-scripts build .env.development",
"build:qa": "npm run build-css && react-scripts build .env.qa",
"build:pro": "npm run build-css && react-scripts build .env.production"

but if I execute a build:* command, the file loaded is always .env.production because the NODE_ENV is production. Is it possibile to load the others .env file with "build:* command?

I solved my question using react-app-env and renaming the .env file.

Dev/Prod Server     | .env file
---------------------------------------------
qa                  | qa.env

And the build:qa scripts, for example, became:

"build": "npm run build-css && react-scripts build",
"build:qa": "react-app-env --env-file=qa.env build"

I'm the author of switchenv . It's a command line tool for quickly switching .env file from Keepass entries (content from the Notes field)

Simply running yarn switchenv development would replace your .env file.

Run yarn switchenv production and replace your .env file with the production one.

Basically, all your .env files are stored as entries in a Keepass file. The content of the .env file for each entry should be stored in the Note field. Using switchenv reads that Keepass file and replaces the .env file with the Notes of the entry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM