在Shell脚本中为React应用设置环境变量 [英] Setting environment variables in a shell script for a React app

查看:105
本文介绍了在Shell脚本中为React应用设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to set some environment variables in a powershell (and bash) script and read them in a ReactJS application. The shell script is simple:

$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 正确地拾取,但是没有变量(包括 PORT )可通过 process.env 使用反应JavaScript.

The port is being picked up correctly by yarn but none of the variables (including PORT) are available via process.env within the React javascript.

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

我的 package.json 文件没有mods:

No mods to my package.json file:

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

我想念什么? Get-ChildItem 显示变量已在环境中正确设置.

What am I missing? Get-ChildItem shows that the variables are set correctly in the environment.

我尝试在此处,它不起作用.它还会阻止终端接收任何输出:

I tried the solution listed here and it doesn't work. It also blocks the terminal from receiving any output:

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

结果相同.

编辑#2:值得注意的是,linux/bash中的行为完全相同(这是一个很好的石蕊测试方法,因为我已经在bash中进行了大约1000亿次的测试)-yarn正确设置了端口,但是没有任何信息使它进入react应用程序:

Edit #2: It's worth noting that the behavior is exactly the same in linux/bash (which is a good litmus test cuz I've done this in bash about a 100 billion times) - yarn sets the port correctly but none of the info makes it into the react app:

#!/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

因此,这可能与powershell无关.

So this likely has nothing to do with powershell.

推荐答案

您要使用的每个环境变量都必须以 REACT_APP _ 为前缀根据 create-react-app的文档:

Every environment variable you wish to consume must be prefixed with REACT_APP_ as per the documentation of create-react-app:

注意:您必须创建以REACT_APP_开头的自定义环境变量.除NODE_ENV以外的任何其他变量都将被忽略,以避免意外地在机器上公开可能具有相同名称的私钥.更改任何环境变量都将要求您重新启动开发服务器(如果正在运行).

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.

这篇关于在Shell脚本中为React应用设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆