2016 年 ES6 发布,Chrome Canary 对新 ECMA-Script 的支持率达到 93%。
所以我尝试以 ES6 的方式使用模块。
喜欢:
( http://exploringjs.com/es6/ch_modules.html#_default-exports-one-per-module )
Or a class:
//------ MyClass.js ------
export default class { ··· } // no semicolon!
//------ main2.js ------
import MyClass from 'MyClass';
const inst = new MyClass();
为了玩转,我制作了一个 index.html 文件和两个如上所述的文件,其中包含 MyClass 的一些简单内容,例如:
constructor(name) {
this.name = name;
this.currentSpeed = 25;
}
所以我有:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<module src="MyClass.js"></module>
<script type="text/javascript" src="main2.js"></script>
</head>
<body>
<p>Hallo:)</p>
</body>
</html>
在index.html
export default class {
constructor(name) {
this.name = name;
this.currentSpeed = 25;
}}
在 MyClass.js 中和
import MyClass from 'MyClass';
const inst = new MyClass();
在 main2.js 中
这对我不起作用。每次在 main2.js 中导入都会出错。 有人有能力帮助我吗?
最佳答案
这里有两件事:
- 浏览器实际上尚未提供 ECMAScript 模块支持。我想当他们这么做的时候,这件事将会传遍 Twitter。
- 您需要使用
<script type=module src=modulescript.js>
在 HTML 中使用模块脚本。 (还有针对 worker 的new Worker("moduleworker.js", {type:"module"})
,但目前还不支持。)
关于javascript - ES6 完整项目中的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35605688/