Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't call a function from js file imported as type module

I am writing my Javascript files in ES6 using module imports. Using type='module' is now supported on most modern browsers to allow for proper parsing of import statements. script type="module https://caniuse.com/#feat=es6-module

I built an HTML select element were onchange() calls a function from one of my module files using select onchange="someFunction()" but an error is always thrown saying the function is not defined when the on change event occurs. I tested the same function inline and also without using the type="module" with no issues as expected.

Is this a bug? Does it have to do with module scripts being deferred by default? Am I missing something simple?

I understand I could avoid this issue by using Webpack or a framework but I really wanted to try and use just vanilla javascript without any extras. I believe also creating this select element in the js then attaching to the dom would also solve the issue as well.

like image 277
Stevenfowler16 Avatar asked Sep 12 '25 01:09

Stevenfowler16


2 Answers

Modules don't create globals. Everything is scoped within the module.

If you want to bind an event handler, then do it from inside the module using addEventListener and not using an onXxxxx attribute.

like image 162
Quentin Avatar answered Sep 13 '25 14:09

Quentin


you can use this to use function when use script with type module

            <button onclick="import('/modules/script.js').then(o=> o.showdialog())">

and use export in script.js

export function showdialog() {}
like image 39
hossein sedighian Avatar answered Sep 13 '25 14:09

hossein sedighian