如何配置我的 package.json 文件以从我的操作系统中设置的环境变量中读取?

Dav*_*ave 5 proxy environment-variables reactjs package.json

我正在使用 React 16.12.0。我在 package.json 中配置了以下“代理”

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.0",
    "@testing-library/user-event": "^7.2.1",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "3.3.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "proxy": "http://localhost:9090",
Run Code Online (Sandbox Code Playgroud)

这对开发非常有用,但是当我将我的网站移至 qa 和生产时,我希望能够从某种环境变量中读取我的 package.json 文件。我如何编写我的 package.json 或配置我的应用程序以根据环境使用不同的 URL,或者至少在我的环境中设置一个变量?

jdo*_*roy 4

来自文档:https ://create-react-app.dev/docs/proxying-api-requests-in-development/

Keep in mind that proxy only has effect in development (with npm start), and it is up to you to ensure that URLs like /api/todos point to the right thing in production.

As an alternative, you can use environment variables instead: https://create-react-app.dev/docs/adding-custom-environment-variables/

You should create .env.development and .env.production files at the root of your project:

# .env.development

REACT_APP_PROXY=http://localhost:9090
Run Code Online (Sandbox Code Playgroud)
# .env.production
REACT_APP_PROXY=<some other domain>
Run Code Online (Sandbox Code Playgroud)

And consume it on the react app:

# .env.development

REACT_APP_PROXY=http://localhost:9090
Run Code Online (Sandbox Code Playgroud)