如何将typescript文件导入到script标记中



我要做的是将typescript文件中的对象导入到脚本标记中

这就是我试图做的

<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>

我不确定这是否可能,但我的react应用程序正在#app-root中呈现,我正在尝试从我的配置中处理我的API密钥。当我运行这个程序时,什么都不会发生,但如果我添加静态值,它似乎可以工作。

我希望通过将变量传递给脚本src,脚本将成功执行。

typescript文件需要编译/转换为JS(转换为.JS文件(才能在浏览器中使用。

您可以在此处在线编译TS文件:https://www.typescriptlang.org/play并将输出复制到.js 中

通过命令行安装(假设您在Windows上(

npm install typescript // add -g if you want to install it globally
cd intoYourFolder // change directory to the folder where you have the .ts file
tsc *.ts // this will compile all typescript files in the directory
tsc yourFile.ts // this will compile only a specific file

不,不可能读取script标记中的ts文件(至少在不首先将其编译为js的情况下(。

但是,您可以使用环境变量,并让react脚本将其编译到模板中,就像每次启动开发服务器或运行构建时一样。

从这里开始:

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>

最后一个想法是,你可以在需要的地方以首选的react方式包含你的谷歌地图依赖项:使用react插件。看看这个。它将负责为您加载/卸载api,并且您可以在加载api时从配置传入密钥:

https://www.npmjs.com/package/@react谷歌地图/api

最新更新