javascript - ES6 完整项目中的模块

标签 javascript class module project ecmascript-6

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 中导入都会出错。 有人有能力帮助我吗?

最佳答案

这里有两件事:

  1. 浏览器实际上尚未提供 ECMAScript 模块支持。我想当他们这么做的时候,这件事将会传遍 Twitter。
  2. 您需要使用<script type=module src=modulescript.js>在 HTML 中使用模块脚本。 (还有针对 worker 的 new Worker("moduleworker.js", {type:"module"}),但目前还不支持。)

关于javascript - ES6 完整项目中的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35605688/

相关文章:

javascript - 如何将 ng-repeat 值传递给 Controller

c# - 将成员委托(delegate)给经典函数有更多优点或缺点?

c++ - 如何在不加前缀 [类名]::的情况下在友元函数中使用静态成员:

python - 无法在scrapy中导入项目

perl - 在 Perl 中,如何确定我的文件是作为模块使用还是作为脚本运行?

javascript - react : Firing a custom alert from multiple components using an existing component having its own styles

javascript - jQuery Validation : $. data($ ('form' )[0], 'validator' ).settings 返回 undefined

c - 如何在不引用 c 对象的情况下导入使用 FFI 的 haskell 模块?

javascript - 如何从 Promise .then 处理程序触发 .fail 处理程序

Python/Psychopy : Instantiating multiple circle objects from a class