Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

reactjs - create react app not picking up .env files?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With create react app, you need to prefix REACT_APP_ to the variable name. ex:

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

CRA Docs on Adding Custom Environment Variables:

Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...