如何在不导入jsx的情况下在jsx文件中使用配置变量?

时间:2019-05-25 10:20:02

标签: reactjs

我在 public / environment.js 中创建了1个配置文件,并从配置文件中返回对象。

我还在 public / index.html

中包含了此配置文件

如何在不导入的情况下在所有.jsx文件中使用此对象?

我会关注

  

public / environment.js

glbVar = {
  HOST_ENV: "REACT_APP_HOST_ENV",
  SOCKET_ENV: "REACT_APP_SOCKET_ENV"
};

我在 index.html 中包含了 environment.js 文件,并且能够使用此 glbVar

  

public / index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="theme-color" content="#000000" />

  <script src="./environment.js"></script>

  <title>React App</title>
</head>

<body>
  <div id="root"></div>
</body>

<script>
  console.log("glbVar index file", glbVar);
</script>

</html>

但是我无法在 .jax 文件中直接使用此 glbVar

如何在不导入环境.js文件的情况下在所有.jsx文件中使用此glbVar

预先感谢...

1 个答案:

答案 0 :(得分:1)

首先,您需要像这样导出该全局变量:

export const glbVar = {
  HOST_ENV: "REACT_APP_HOST_ENV",
  SOCKET_ENV: "REACT_APP_SOCKET_ENV"
};

然后在您的 .jsx文件中将其导入:

import { glbVar } from "./path-to-your-environment.js-file" // note that this is the relative path to your environment file`