javascript - 如何在加载事件中加载 html 页面中的 es6 模块

标签 javascript es6-modules

我是 ES6 模块的新手,请告诉我如何从网页上的 ES6 模块导入函数,然后在按钮的单击事件上使用该函数。

到目前为止,我已在名为 (ES6Part3Module.js) 的文件中定义了此模块:

export function sayHello() {
return "hi there folks";
}

然后在我的 html 页面中,我以这种方式加载模块:

`<script src="ES6Part3Module.js" type="module"`>`</script`>

我现在想要某种方法为页面上的按钮创建点击处理程序:

`<button id="sayHelloButton"`>Say Hello`</click`>

它从我的 ES6 模块调用 sayHello() 函数。

我尝试在我的页面上创建本地(模块)脚本:

`<script type="module"`>
import sayHello from "ES6Part3Module.js";
window.hello = sayHello;
`</script`>

然后在页面上加载一些jquery:

$( function() {

$("#sayHelloButton").click(function() {
alert(hello());
});

});

但是当单击 html 页面上的按钮时,出现错误,提示 hello 未定义。

请让我知道我做错了什么?

最佳答案

这是使用旧版本的 system.js 的答案。我对使用新版本的 system.js 的答案感兴趣。

<!--
ref (https://livebook.manning.com/#!/book/angular-2-development-with-typescript/chapter-2/159, p 159, listing2.7)
-->
<!--unpkg is a fast, global content delivery network for everything on npm-->
<script src="//unpkg.com/es6-promise@3.0.2/dist/es6-promise.js"></script>
<script src="//unpkg.com/traceur@0.0.111/bin/traceur.js"></script>
<!--system js, version that was released in 21/08/2016-->
<script src="//unpkg.com/systemjs@0.19.37/dist/system.src.js"></script>

<script>
System.import('./ES6Part3Module.js').then(ES6Part3Module => {
  window.hello = ES6Part3Module.sayHello;
});
</script>

<script>
$( function() {

$("#sayHelloButton").click(function() {
alert(hello());
});

});
</script>

关于javascript - 如何在加载事件中加载 html 页面中的 es6 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46809853/

相关文章:

javascript - onclick返回和javascript

javascript - 延迟解析始终在 try catch 内

javascript - 删除子节点

javascript - 使用 Jest 和 @std/esm 模拟 Node 模块

javascript - ES6 和多次导出的导入问题

javascript - 如何导出从异步函数获取值的变量

javascript - 从应用程序根目录导入/需要的 NPM 依赖项

javascript - 当对象更新超出范围时如何更新 angularJS 中的 View

java - 我无法让 servlet 使用 ajax 和 xml 将参数发送到 jsp 文件

javascript - ES2015 "import"在带有 --harmony_modules 选项的 Node v6.0.0 中不工作