首页 > 解决方案 > 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.

标签: javascripthtmlreactjstypescriptdom

解决方案


不,它不可能读取脚本标记中的 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 时从配置中传递您的密钥:

https://www.npmjs.com/package/@react-google-maps/api


推荐阅读