javascript - How to import typescript file into script tag
问题描述
What I am trying to do is import an object from my typescript file into a script tag
This is what I am trying to do
<div id="app-root"></div>
<script>
import {config} from '../config.ts';
let script = document.createElement('script');
script.src = `https://maps.googleapis.com/maps/api/js?key=${config.GOOGLE_MAPS_KEY}`;
document.getElementsByTagName('script')[0].parentNode.appendChild(script);
</script>
I'm not sure if this is possible, but my react app is being rendered in #app-root and I am trying to handle my API key from my config. When I run this nothing happens, but If I add the static value instead it seems to work.
What I expect to happen is by passing the variable in to the script src, the script will execute successfully.
解决方案
不,它不可能读取脚本标记中的 ts 文件(至少没有先将其编译为 js)。
但是,您可以做的是改用环境变量,并让 react-scripts 将其编译到您的模板中,就像您每次启动开发服务器或运行构建时所做的那样。
从这里开始:
https://create-react-app.dev/docs/adding-custom-environment-variables
.env
首先,在我们项目的根目录下创建一个 env 文件
接下来,让我们将环境变量添加到此文件中:
REACT_APP_GOOGLE_MAPS_KEY=<your key>
最后,让我们修改 index.html 以引用我们的环境变量:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=%REACT_APP_GOOGLE_MAPS_KEY%"></script>
作为最后的想法,您可以在需要的地方以首选的反应方式包含您的谷歌地图依赖项,而不是遇到所有这些麻烦:通过使用反应插件。看一下这个。它将为您加载/卸载 api,并且您可以在加载 api 时从配置中传递您的密钥:
推荐阅读
- reactjs - 调度触发后使用状态
- c++ - 行列式使用高斯消元法,C++
- azure - func.exe 如何识别从 VS2019 运行的特定函数?
- django - 如何为 xml 使用 jinja 模板?
- javascript - 排除 if between,但更复杂
- microsoft-teams - 使用 HttpPOST Action 表单 Teams 消息进行 POST 调用
- spring-security - 如何在 Spring Boot Oauth (spring-security-jwt) 中使用椭圆曲线签署 JWT?
- git - 暂时恢复到以前的提交,进行更改,保留更改并返回到最新的提交?
- arrays - 是否可以在不激活其 DidSet 属性的情况下使数组为空?
- javascript - 按键计算对象数组(动态)的百分比