在 React 应用程序的 shell 脚本中设置环境变量

Setting environment variables in a shell script for a React app

我正在尝试在 powershell(和 bash)脚本中设置一些环境变量,并在 ReactJS 应用程序中读取它们。 shell 脚本很简单:

$env:AUTHDOMAIN="some.domain.com"
$env:AUTHCLIENTID="bunch-o-characters"
$env:AUTHCALLBACK="http://somewhere:3002/callback"
$env:AUTHAUDIENCE="auth-audience"

$env:PORT=3002

# Get-ChildItem Env:

yarn start

端口被 yarn 正确获取,但是 none 的变量(包括 PORT)可通过 React process.env 在 React javascript.

console.log("domain     : " + process.env.AUTHDOMAIN);
...
domain     : undefined App.js:33

我的 package.json 文件没有模组:

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

我错过了什么? Get-ChildItem 表明变量在环境中设置正确。

编辑:我尝试了 here 列出的解决方案,但它不起作用。它还会阻止终端接收任何输出:

$ ($env:AUTHDOMAIN="some.domain.com") -and (yarn start)

同样的结果。

编辑 #2:值得注意的是,在 linux/bash 中的行为 完全相同(这是一个很好的试金石,因为我在 bash 大约 1000 亿次)- yarn 正确设置了端口,但是 none 的信息使其进入了 React 应用程序:

#!/bin/sh

export AUTHDOMAIN="some.domain.com"
export AUTHCLIENTID="bunch-o-text"
export AUTHCALLBACK="http://somewhere:3001/callback"
export AUTHAUDIENCE="auth-audience"

export PORT=3002

yarn start

所以这可能与功率无关shell。

您希望使用的每个环境变量都必须以 REACT_APP_ 为前缀 根据 documentation of create-react-app:

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.