I want to call a js function, client side, within an Astro template.
I could use this with 2 script tags, the first to attach the variables to the window:
---
const { myVar } = Astro.locals;
---
<script is:inline define:vars={{ myVar }}>
window.myVar = myVar
</script>
and the second to call my function:
<script>
import { someFunction } from "@/utils"
someFunction(window.myVar)
</script>
Alternatively I could use React:
---
const { myVar } = Astro.locals;
---
<RunMyFunction client:only var={myVar} />
function RunMyFunction({myVar}) {
someFunction(myVar);
return null;
}
But this seems messy and introduces a dependency on React.
I read in the docs about attaching variables to html elements, using data attributes, and then accessing them in scripts - but I don't need an html element other than the script tag, and adding a data attribute to the script tag will make it infer is:inline, so I can't then import my function.
Is there way to call Vanilla JS functions, passing variables to them, with the neat API that frameworks like React have?