#How can I share JavaScript between components in the browser?

4 messages · Page 1 of 1 (latest)

acoustic rock
#

I am new to JavaScript and very new to Astro, so apologies if this is a dumb question. I can't find it with google and it worries me that nobody else has this problem, so I must be doing something wrong.

I read https://docs.astro.build/en/guides/client-side-scripts/ but it doesn't say how to use any of the imported scripts.

I want share some simple functions between components. But not during build, but in the browser. For example:



<script>
const label = document.querySelector(".label");
label.innerText = putInStars("hello world");
</script>

<div>
<span class="label"></span>
</div>

In the browser, I want the span to contain: ★★★hello world★★★.

I made a script utilities.js with a function putInStars but it is always undefined. No matter if I make it global, put export in front of it, etc.

I am not using a framework, just pure Astro and vanilla JavaScript.

So how can I use putInStars in all components?

elfin spadeBOT
#
Quiet in here?

It looks like no-one has responded to your question yet. People might not be available right now or don’t know how to answer your question. Want an answer while you wait? Try asking our experimental bot in #1095492539085230272.

lusty aurora
#

You can export the putInStars function and then import into your <script> tag like this: ```html
<script>
import { putInStars } from '../utilities'

const label = document.querySelector(".label");
label.innerText = putInStars("hello world");
</script>
``` Also, I recommend turning utilities.js into a .ts file

cerulean canyon