Answer a question

I am working on a small project including react frontend and Java backend with two environments.

I struggle on the idea how to work with multiple environemnts, I declare API url using axios:

export default axios.create({
  baseURL: `http://api.dev.project.local/api/v1`,
});

But this works only for one environment, how to change API url after the package is built? I don't think it is a good practise to create two builds (one for dev and one for prod), because it could create mess inside artifacts manager (we use Azure Artifacs Feed).

How do you solve this problem?

Answers

In case you are with create-react-app, and only need local and production environment go with Adding Custom Environment Variables build-in feature. Otherwise, a useful alternative is env-cmd.

Install env-cmd, as a development dependency:

npm i -D env-cmd

Add .env file (at project root, same for all environments):

REACT_APP_API_ENDPOINT = https://default.example.com

Add .env.qa file:

REACT_APP_API_ENDPOINT = https://qa.example.com

Add .env.staging file:

REACT_APP_API_ENDPOINT = https://stage.example.com

Add .env.production file:

REACT_APP_API_ENDPOINT = https://production.example.com

Update package.json

{
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "build:qa": "env-cmd -f .env.qa npm run-script build",
    "build:staging": "env-cmd -f .env.staging npm run-script build",
  }
}

Note that default start and build create-react-app commands are using .env and .env.production respectively, and have no need of env-cmd.

Ready to use in our code

const baseUrl = process.env.REACT_APP_API_BASE_URL;

And, we also can use env-cmd for start command at development environment.

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐