【问题标题】:Unable to get env variables in public/index.html for react app无法在 public/index.html 中获取反应应用程序的环境变量
【发布时间】:2021-10-04 01:31:51
【问题描述】:

试图从 public/index.html 文件中获取环境值

尝试使用 config.js 中的 window.APPDYNAMICS_KEY

public/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <script src="src/config.js"></script>
    <script charset='UTF-8'>
      if(window.APPDYNAMICS_KEY){
....

src/config.js

export default {
  STAGE: process.env.NODE_ENV || 'development',
  ...
  APPDYNAMICS_KEY: process.env.REACT_APP_APPDYNAMICS_KEY,
};

.env

...
REACT_APP_APPDYNAMICS_KEY=SAMPLE-KEY HERE
HTTPS=true

【问题讨论】:

  • appdynamics_config.js 是你的 react 应用源代码的一部分吗?如果没有,则将其包含在您的 app.js 文件中。
  • 我们添加了 >> 在 就足够了吗?
  • 否,因为 create react app 神奇地将所有 process.env 实例替换为 window 但条件是您的文件必须是 CRA 构建过程的一部分。
  • 更新了我的代码,但现在它遇到了 Uncaught SyntaxError: Unexpected token 'stackoverflow.com/questions/48434897/…

标签: javascript reactjs


【解决方案1】:

原来我不需要导入任何脚本。

只需在我的 index.html 中使用以下 '%REACT_APP_APPDYNAMICS_KEY%'

public/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <script charset='UTF-8'>
      if('%REACT_APP_APPDYNAMICS_KEY%'){
....

.env

...
REACT_APP_APPDYNAMICS_KEY=SAMPLE-KEY HERE
HTTPS=true

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 1970-01-01
    • 2019-02-22
    • 2020-10-30
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2017-03-31
    相关资源
    最近更新 更多