Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, its not possible to read a ts file in script tag (atleast without first compiling it to js).

What you can do however, is to use environment variables instead, and let react-scripts compile it into your template as it already does everytime you start the dev server or run the build.

start here:

https://create-react-app.dev/docs/adding-custom-environment-variables

First, create an env file called .env at the root of our project

Next, lets add our environment variable to this file:

REACT_APP_GOOGLE_MAPS_KEY=<your key>

Finally, lets modify index.html to reference our environment variable:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=%REACT_APP_GOOGLE_MAPS_KEY%"></script>

As a final thought, instead of going to all this trouble, you could instead include your google maps dependency where needed in the preferred react way: by using a react plugin. Check this out. it will take care of loading/unloading the api for you, and you can pass your key in from config when you load the api:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...