首页 > reactjs > 公共index.html中的CRA变量替换

公共index.html中的CRA变量替换 (CRA variable replacement in public index.html)

问题

我理解的目的%PUBLIC_URL%,但是我也理解并观察到你不能PUBLIC_URL在开发(本地)运行期间设置并替换它。我遇到了以下情况。

我必须引用托管在特定于部署环境的服务器上的脚本资源。我需要从不同的主机获取此资源,具体取决于这是开发运行还是部署(例如QA):

  1. 如果在本地运行,那么脚本需要来自“ https:// my-dev-server ”(也就是说,在本地运行时,脚本应该从DEV环境中提取)
  2. 如果部署到DEV,QA或PROD,那么脚本需要来自 %PUBLIC_URL%

如果我使用脚本标记,例如...,这已经适用于已部署的环境(上面的#2)

<script src="%PUBLIC_URL%/a/b/c/my-script.js></script>

但是,当在本地运行时,%PUBLIC_URL%用“”(空字符串)替换,所以我的脚本从“/a/b/c/my-script.js”获取,这导致404。

如何替换自定义环境变量,例如“DEPLOY_HOST”和脚本标记,如...

<script src="https://%DEPLOY_HOST%/a/b/c/my-script.js></script>

注意:使用react-scripts v2.1.3

解决方法

在根目录中创建两个.env文件

// file name: .env.development
REACT_APP_MY_API=https://dev.api
// file name: .env.production
REACT_APP_MY_API=https://production.api

在index.html中,您现在可以执行此操作:

<script>
  console.log('%REACT_APP_MY_API%'); // This will change based on development or production
</script>

或者你可以:

<script src="%REACT_APP_MY_API%/a/b/c/my-script.js"></script>

问题

I understand the purpose of %PUBLIC_URL%, however I also understand and have observed that you cannot set PUBLIC_URL and have it replaced during a development (local) run. I have run into the following situation.

I have to reference a script resource which is hosted on a server specific to the deployment environment. I need to grab this resource from a different host, depending on whether this is a development run or is deployed (e.g. QA):

  1. if running locally, then the script needs to come from "https://my-dev-server" (that is, when running locally, the script should be pulled from the DEV environment)
  2. if deployed to DEV, QA, or PROD, then the script needs to come from %PUBLIC_URL%

This already works for deployed environments (#2 above) if I use a script tag such as ...

<script src="%PUBLIC_URL%/a/b/c/my-script.js></script>

However, when running locally, %PUBLIC_URL% is replaced with "" (empty string), so my script is fetched from "/a/b/c/my-script.js" which results in a 404.

How can I have a custom environment variable replaced, e.g. "DEPLOY_HOST", and a script tag like ...

<script src="https://%DEPLOY_HOST%/a/b/c/my-script.js></script>

Note: using react-scripts v2.1.3

解决方法

Create two .env file in your root directory

// file name: .env.development
REACT_APP_MY_API=https://dev.api
// file name: .env.production
REACT_APP_MY_API=https://production.api

In your index.html, you can do this now:

<script>
  console.log('%REACT_APP_MY_API%'); // This will change based on development or production
</script>

Or you can:

<script src="%REACT_APP_MY_API%/a/b/c/my-script.js"></script>
相似信息