How to use ES Modules with functions in HTML file

Hello all,

I am having trouble using ES modules with HTML file.
So, I have two separate js files, one of which is imported into the other, the second one has functions, which I need to use inside the HTML file for an <a> tag.

Now, in Google Dev Tools console.log it says that the function is not defined, I am guessing this is because I am using the first js file as a type="module".
HTML file
JS file

Is there a way to use these functions from the main js file or should I just join the data I am having from the two js files into one js file?


1 Like

What console.log and in which file is it located? Which function is showing not defined?How can we replicate what you are seeing?

1 Like

Hello, thank you for replying first of all.
So, if you downloaded the repo, with the css file as well, after you open the template.html there are two arrows around the main container div, which are the controls for the slides.
These are connected to the plusSlides function, which are advancing or reversing the slides depending in which direction are you pressing.

Now, when the template.js is imported into the HTML file as type="module", i get an error stating that the plusSlides function is not defined in the Google Chrome Dev Tools. This is what I am guessing that if the js file is imported as module, it cannot recognize the functions used inside the HTML file in the aforementioned <a> tag.
This is how you can replicate the error.
Hope that makes sense.

As far as I know, you have to attach the function to the global object because of the scoping rules with modules. Or don’t use an inline handler.

globalThis.plusSlides = plusSlides;

Module-defined variables are scoped to the module unless explicitly attached to the global object. On the other hand, globally-defined variables are available within the module.

1 Like

Thank you so much. It works as a charm.