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

♀尐吖头ヾ 提交于 2021-02-08 06:33:37

问题


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.


回答1:


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.




回答2:


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() {}


来源:https://stackoverflow.com/questions/53069695/cant-call-a-function-from-js-file-imported-as-type-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!