create-react-app 在构建期间,REACT_APP_环境变量未替换公共文件夹js文件,

f4t66c6m  于 20天前  发布在  React
关注(0)|答案(1)|浏览(19)

描述bug

我希望React应用在部署新版本时通知所有浏览者,以便最终用户可以在不出现任何错误消息的情况下尝试刷新打开的页面,并实现懒加载。
有一个循环来检查包含最新应用程序版本的文件public/config.js:

window.__env = {
    // other variables ....
    "CURRENT_VERSION": process.env.REACT_APP_VERSION
}

但是似乎变量process.env.REACT_APP_VERSION在构建过程中没有被替换?

你尝试恢复依赖项了吗?

我按照https://create-react-app.dev/docs/adding-custom-environment-variables#referencing-environment-variables-in-the-html中的文档进行了操作,但似乎只有public/index.html文件起作用。

你在用户指南中搜索了哪些术语?

我认为这两个问题是相关的。
#7953
#8004
而且#8004(评论)提到:
在大多数情况下,这个问题可以通过在项目中运行自定义脚本来轻松解决,该脚本在react-scripts构建之前运行。
但是为什么public/index.html可以工作?我认为自定义脚本可能太复杂了。需要一个通用的机制。

环境

Environment Info:

  current version of create-react-app: 4.0.2
  running from /Users/shanchuanxu/.config/yarn/global/node_modules/create-react-app

  System:
    OS: macOS 10.15.7
    CPU: (8) x64 Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
  Binaries:
    Node: 12.12.0 - /usr/local/bin/node
    Yarn: 1.22.4 - /usr/local/bin/yarn
    npm: 6.11.3 - /usr/local/bin/npm
  Browsers:
    Chrome: 88.0.4324.192
    Edge: Not Found
    Firefox: 84.0.2
    Safari: 14.0.3
  npmPackages:
    react: ^16.13.0 => 16.14.0
    react-dom: ^16.13.0 => 16.14.0
    react-scripts: 4.0.1 => 4.0.1
  npmGlobalPackages:
    create-react-app: Not Found

重现步骤

(在这里写下你的步骤:)

预期行为

public/config.js中的环境变量可以被替换为字符串。

实际行为

(写下发生了什么。请添加截图!)

可复现示例

(粘贴一个示例项目的链接和精确的重现问题的说明。)

5t7ly7z5

5t7ly7z51#

我找到了一个解决这个问题的方法,使用内联脚本:

<html>
    <head>
        <script>
            window.__env = {
                // other variables ....
                "CURRENT_VERSION": "%REACT_APP_VERSION%"
            }
        </script>
    <head>
</html>

相关问题