创建React App:在index.html中使用环境变量 [英] Create React App: using environment variables in index.html

查看:757
本文介绍了创建React App:在index.html中使用环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法注入环境变量,例如 REACT_APP_MY_API index.html 文件中?

Is there a way to inject environment variables, e.g. REACT_APP_MY_API into the index.html file?

根据,它可以完成,但我似乎无法使其正常工作。

According to this, it can be done, but I can't seem to get it to work.

REACT_APP_MY_API=https://something.com



index.html



index.html

<script type="text/javascript">
  console.log("%REACT_APP_MY_API%") // undefined 
  console.log("%NODE_ENV%") // development
</script>


推荐答案

我刚刚尝试了(几乎)新的CRA设置

I just tried with an (almost) new CRA setup and it works.

<head>
  <title>React App</title>
  <script type="text/javascript">
   console.log("%REACT_APP_TEST%") // OK
   console.log("%NODE_ENV%") // development
  </script>
</head>

您是否尝试重新启动服务器?
我只是尝试用您的示例更改测试变量,并且在您重新启动开发服务器时它可以工作。

Did you try restarting the server? I just tried changing the test variable with your example and it works if you restart the development server.

正如评论中指出的那样,官方文档CRA的 a部分

As someone pointed out in the comments, the official documentation of CRA has a section about that.

这篇关于创建React App:在index.html中使用环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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