2017-10-18 134 views
1

我是ES6模块的新手,请您告诉我如何从网页上的ES6模块导入功能,然后使用该功能在按钮上点击事件。如何在加载事件的HTML页面中加载es6模块

到目前为止,我已经定义在一个叫(ES6Part3Module.js)文件的模块:

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

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

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

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

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

其中调用sayHell o()函数来自我的ES6模块。

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

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

,然后有它运行在加载网页上的一些jQuery的:

$(function() { 

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

}); 

但当按钮点击html页面,我得到一个错误,说你没有定义。

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

回答

0

这是使用旧版本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/[email protected]/dist/es6-promise.js"></script> 
<script src="//unpkg.com/[email protected]/bin/traceur.js"></script> 
<!--system js, version that was released in 21/08/2016--> 
<script src="//unpkg.com/[email protected]/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>