create react app not picking up .env files?

2019-04-03 10:45发布

问题:

I am using create react app to bootstrap my app.

I have added two .env files .env.development and .env.production in the root.

My .env.development includes:

API_URL=http://localhost:3000/api
CALLBACK_URL=http://localhost:3005/callback

When I run my app using react-scripts start and console out process.env it spits out

{ NODE_ENV: "development", PUBLIC_URL: "" }

I've tried different things, but its just not picking up the veriables in my development file, what am I doing wrong?!

Directry structure is:

/.env.development
/src/index.js

Package.json script is:

"start": "export PORT=3005; npm-run-all --parallel server:start client:start",
    "client:start": "export PORT=3005; react-scripts start",
    "server:start": "node server.js",
    "build": "react-scripts build",

Edit:

@jamcreencia correctly pointed out my variables should be prefixed with REACT_APP.

Edit 2

It works okay if I name the file .env but not if I use .env.development or .end.production

回答1:

With create-react-app, you need to prefix REACT_APP_ to the variable name to be able to access it.

Example:

REACT_APP_API_URL=http://localhost:3000/api
REACT_APP_CALLBACK_URL=http://localhost:3005/callback

See more info here



回答2:

If you want to use multiple environment like .env.development .env.production

use dotenv package

add .env.development and .env.production in project root folder

and your package.json

"scripts": {
    "start": "react-app-rewired start",
    "build-dev": "dotenv -e .env.development react-app-rewired build",
    "build-prod": "dotenv -e .env.production react-app-rewired build",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-scripts eject"   
},

then build according to environment like

npm run-script build-dev 


回答3:

For this purpose there is env-cmd module. Install via npm npm i env-cmd then in your package.json file in scripts section:

  "scripts": {
    "start": "env-cmd .env.development react-scripts start",
    "build": "GENERATE_SOURCEMAP=false env-cmd .env.production react-scripts build",
  }

In your project root you have to create two files with the same env variables but with different values:

.env.development
.env.production

Then exclude them from public. For this in your .gitignore file add two lines:

.env.development
.env.production

So this is a proper way to use different env variables for dev and prod.



回答4:

If the .env file works but .env.development or .env.production don't, then create an empty .env file alongside those two. I don't know why but this works for me.