Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - How to set build .env variables when running create-react-app build script?

I'm using the following environment variable in my create-react-app:

console.log(process.env.REACT_APP_API_URL) // http://localhost:5555

It works when I run npm start by reading a .env file:

REACT_APP_API_URL=http://localhost:5555

How do I set a different value like http://localhost:1234 when executing a npm run build?

This is my package.json file:

{
  "name": "webapp",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "0.9.0"
  },
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I imagine you got this working by now, but for anyone else that finds this, you set your default environment variables in a .env file at the root of your "create-react-app" project.

To separate out the variables used when using npm start and npm run build you can create two more env files - .env.development and .env.production.

npm start will set REACT_APP_NODE_ENV to development, and so it will automatically use the .env.development file, and npm run build sets REACT_APP_NODE_ENV to production, and so it will automatically use .env.production. Values set in these will override the values in your .env.

If you're working with other people, and have values specific to your machine only, you can override values in .env.development and .env.production by adding those values to a new file - .env.development.local and .env.production.local respectively.

EDIT: I should point out that the environment variables you have set must start with "REACT_APP_", eg. "REACT_APP_MY_ENV_VALUE".

EDIT 2: if you need more than just development, and production, use env-cmd, as specified by this comment.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...