最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can't call a function from js file imported as type module - Stack Overflow

programmeradmin1浏览0评论

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

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.

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./#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.

Share Improve this question asked Oct 30, 2018 at 17:20 Stevenfowler16Stevenfowler16 1,0201 gold badge10 silver badges22 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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.

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() {}
发布评论

评论列表(0)

  1. 暂无评论