Astro: I can't import a function and use define:vars= inside a script simultaneously

31 views Asked by At

I'm not able to import a function called jsonFetch and use define:vars= simultaneously inside a <script> in Astro

---

// Code related to the Astro backend
const question = { /* data */ };

---

// HTML code

<script define:vars={{ question }}>
    import {jsonFetch} from "../../utils/json-fetch.ts";
</script>

❌ The code above shows me this error:

Uncaught SyntaxError: Cannot use import statement outside a module

✅ But if I remove define:vars={{ question }}, the import works fine

❌ Using <script define:vars={{ question }} type="module"> shows me this error:

GET http://localhost:4322/utils/json-fetch.ts 404 (Not Found)

How can I import a function and keep define:vars=?

Thank you for checking!

2

There are 2 answers

0
Rodrigo João Bertotti On

I managed to do it by using an alternative way of passing server-side variables

---

const question = { 'my': 'question object' };

---

<!-- HTML code-->

<my-question-script data-question={ JSON.stringify(question) }></my-question-script>

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

  class MyQuestionScript extends HTMLElement {
    constructor() {
      super();
      const question = JSON.parse(this.dataset.question);
      console.log(typeof question);
      console.log(typeof jsonFetch);

      // TODO: handle data
    }
  }

  customElements.define('my-question-script', MyQuestionScript);
</script>
0
Mario ECs On

when the script tag in astro has the is:inline property, Astro does not post process that script as normal. That is, everything related to transpilation stops working to leave the file as it is, without any process. In this case the js imports are not carried out, nor are the css imports, etc...

Check the docs: https://docs.astro.build/en/reference/directives-reference/#isinline

Why don't you import the Fetch json from the Front Matter, and pass it through the define:vars={}?