简体   繁体   中英

I am missing something about .env, could you explain it to me?

I have a very, basic, need: to store different endpoints for my APIs according to the environment. Suppose a simple file like this:

API_URL=http://localhost:8080

it should become, for my prod environment:

API_URL=http://myprodServer

and I'd like to have an integration test and a uat endpoint too!

Looking at my package.json I see:

"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",

So my idea is:

  1. Put a command line argument near to "build" and "start" so to specify local and production enviroment files
  2. Have a way to access to said configuration in my app, say config.API_URL

Now, I come from spring boot, and in spring boot I have a file per environment.

I though dotenv could be my solution but I see two strange things on their website:

  1. Please don't commit your.env file --> so, how are my colleagues supposed to build my application? I usually at least push local and test environment, while keeping the uat and production files directly under the server
  2. You should have just one.env file --> ok this one destroys me: if I just have one file how am I supposed to handle several environments???

What am I missing here? Could you help me solve my problem? I'm new to npm so I'm a little confused...

It looks like you are using CRA to develop your React app. If so, your env variables should be REACT_APP_API_URL=http://localhost:8080 . Notice the prefix. If you are using CRA, you must use the prefix. More about that here . If you do this correctly, the variable should be available in your javascript by using process.env.REACT_APP_API_URL .

At work, we each have a copy of the. env files locally, since we don't check it in. We have different .env files for each environment - eg - .env.production , .env.development , .env.stage . We then have a run and build script for each environment in our package.json . Using env-cmd package, our scripts might look like this:

{
...
...
 "start": "react-scripts start",
 "start:stage": "env-cmd .env.stage.local react-scripts start",
 "start:production": "env-cmd .env.production.local react-scripts start",
 "build": "react-scripts build",
 "build:stage": "env-cmd .env.stage.local react-scripts build",
 "build:development": "env-cmd .env.development.local react-scripts build",
...
...
}

Along with this, we also have a git branch per environment so that on stage branch we would run npm run build:stage and deploy to Stage environment. We would do the same for production.

After looking around for a multi-environment setup, this is what I settled on and it works ok. However, I'd be open to improving the process.

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