基于环境(开发/生产)REACT 处理 .env api url 的最佳方法是什么?

What is best way to handle .env api urls, based on enviroments (dev / prod) REACT?

这里是我根据当前环境设置不同APIURL的方式:

开发和生产,在 npm 上,命令设置环境。

是否有一些更优雅的解决方案,因为我的 URL 很长:

Package.json

"scripts": {
    "start": "REACT_APP_BASE_URL=http://test-dev-1323211.us-east-1.elb.amazonaws.com/api/3.0 react-scripts start",
    "build": "REACT_APP_BASE_URL=http://test-1323211.us-east-1.elb.amazonaws.com/api/3.0 react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "prepare": "husky install",
 
  },

您可以通过 dotenv 库使用 .env 文件。 参见:https://create-react-app.dev/docs/adding-custom-environment-variables

编辑:

来自文档

在.env中添加开发环境变量

要定义永久环境变量,请在项目的根目录中创建一个名为 .env 的文件:

REACT_APP_NOT_SECRET_CODE=abcdef

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. Changing any environment variables will require you to restart the development server if it is running.


您可以在 CRA 文档或 DotEnv 文档中阅读更多内容。

解决方案

基本上您可以使用 .env 和 .env.development.local 来分隔 URL。

.env:

REACT_APP_BASE_URL=http://test-1323211.us-east-1.elb.amazonaws.com/api/3.0

.env.development.local:

REACT_APP_BASE_URL=http://test-dev-1323211.us-east-1.elb.amazonaws.com/api/3.0