Building errors when passing server side variables into client side JavaScript on Astro

Following is a fragment of my Astro component client side script:

<script type="module" define:vars={{ id, date }}>
    import { countdown } from '../js/countdown.js';
    countdown(`#${id}`, date);
</script>

The VSCode linter shows the ts error below when hovering '../js/countdown.js':

Cannot find module '../js/countdown.js' or its corresponding type declarations.ts(2307)

It highlights as well the variables id and date showing these errors respectively:

Cannot find name 'id'.ts(2304)
Cannot find name 'date'. Did you mean 'Date'?ts(2552)

The component works as expected on the localhost testing server when executed with the command bun run dev.

Problem comes whenever I try to build the project with bun run build and the building process halts highlighting the errors mentioned above.

My version of Astro is 4.0.1 and at the moment I’m not using SSR.

I’m fairly new to Astro and technologies like typescript. I don’t know if I’m trying to achieve something which is a limitation of the framework. On the documentation seemed legit to me the way I’m passing server side variables into the client script.

Any help will be appreciated.

I tried to pass server side variables to a client side script and a JavaScript module on an Astro component. Was expecting the project to build successfully with the bun run build command.

  • 1

    try this: <script lang="ts" type="module" define:vars={{ id: string, date: string }}>

    – 

  • That was it! I just feel so dumb right now haha. Is there any way we could toss this post into a black hole? Just kidding. Having a blast with Astro so far. Thanks for your reply.

    – 

  • Just posted it, please accept so it can help others.

    – 

  • …or so I thought. Adding lang="ts" did removed the linter errors and the building process went successfully w/o the type="module" but later on browser launches and exception since the script tag don’t support import. It looks like this might be the case: github.com/withastro/astro/issues/370#issuecomment-893490298

    – 




This should fix it with the relevant typescript

<script lang="ts" type="module" define:vars={{ id: string, date: string }}>

Leave a Comment