【发布时间】:2016-06-02 03:25:15
【问题描述】:
在使用 Google Closure Compiler 时如何包含 Ecmascript 6 类?
例如,我在 'stuff/dog.js' 中有一个类:
class dog {
constructor() {
…
}
addLeg() {
this.legs++;
}
}
我想将它包含在“stuff/pound.js”中,这样我就可以写了:
let rex = new Dog();
应该如何处理?我不能使用 stuff.dog 作为类名,因此将调用传递给 goog.provide() 似乎不是一种选择。
感谢您的帮助!
编辑:使用最新的 (20160517 1.0) 版本的 Closure Compiler,这可以用普通的 Ecmascript 6 来处理:
Animal.js:
export default class{
constructor(){
this.legs = [];
}
addLeg(legId){
this.legs.push( legId );
}
}
Dog.js:
import Animal from './Animal';
export default class extends Animal {
constructor(){
super();
[1,2,3,4].forEach(leg=>this.addLeg(leg));
console.log( 'Legs: ' + this.legs.toString() );
}
}
尽管出于某种原因它确实给了我一个警告:Closure Compiler warns "Bad type annotation. Unknown type …" when Ecmascript 6 class is extended
【问题讨论】:
-
你已经在使用闭包编译器了吗?如果你在
ECMASCRIPT_6模式下运行它,ES6 类定义应该以与遗留原型“类”定义相同的方式被识别;他们并不是一个特例。如果不是,则需要将goog.provide('dog')和goog.require('dog')之类的内容添加到单独的文件中。 -
我正在使用它,但我是新手。当您说“以 ECMASCRIPT_6 模式运行”时,您的意思是将 language_in 设置为“ECMASCRIPT6_STRICT”吗?我有那个设置,我尝试了导出和导入、goog.provide() 和 goog.require()、其他一些随机键组合,但似乎没有任何效果......
-
是的,我就是这个意思。这个问题中没有足够的信息来正确回答(闭包有很多选项/标志,所以最好有一个你尝试过的完整例子),但是:你可能想考虑使用
goog.module,较新的系统表现得更像其他 node.js 模块系统,尽管它仍然是独立于路径的(你可以从任何地方 goog.provide() 名称)。 Here's a random example 使用带有goog.module()、goog.require()和exports的 ES6 类。
标签: javascript ecmascript-6 google-closure-compiler