How to import typescript file into script tag

Viewed 1682

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.

2 Answers

No, it's not possible to read a ts file in script tag (at least 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, let's 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

The typescript files need to be compiled/converted to JS (to a .js file) in order to be used from the browser.

You can compile your TS file online here: https://www.typescriptlang.org/play and copy the output in .js

or

Install it via the command line (assuming you are on 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
Related