How to import a function into a script in Astro using TypeScript?

28 views Asked by At

I have a custom jsonFetch(..) function for performing PUT requests to my external backend, but for some reason, I can't import it inside the <script> tag

---

// Code related to the Astro backend

---

// HTML code

<script type="module">
   // Attempt 1
   import {jsonFetch} from "../../utils/json-fetch";
  
   // Attempt 2
   // const {jsonFetch} = await import("../../utils/json-fetch");
</script>

// Attempt 3
// <script src="../../utils/json-fetch.ts" type="text/javascript"></script>

All import attempts show this error in the browser:

GET http://localhost:4321/utils/json-fetch net::ERR_ABORTED 404 (Not Found)

The error makes sense because the json-fetch.ts file is located inside the src folder rather than in the public folder.

I don't think this is the best practice, but if I move json-fetch.ts to the public folder, I get a syntax error when importing the script, maybe because it's a TypeScript file

Thank you so much!

1

There are 1 answers

4
mb21 On BEST ANSWER

You need to remove type="module":

<script>
  import { jsonFetch } from "../../utils/json-fetch";
</script>

From the docs:

Astro will not process your script tags in some situations. In particular, adding type="module" or any attribute other than src to a <script> tag will cause Astro to treat the tag as if it had an is:inline directive.