【问题标题】:Include an Ecmascript 6 class using Google Closure Compiler?使用 Google Closure Compiler 包含一个 Ecmascript 6 类?
【发布时间】: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


【解决方案1】:

ES6 类可以分配给命名空间:

stuff.dog = class { } 
new stuff.dog();

【讨论】:

  • 谢谢!我使用您的答案和 Jeremy 关于 goog.module() 的建议让它工作。我将添加另一个答案,以便添加格式……
【解决方案2】:

使用 Jeremy 和 Chad 的答案(谢谢,伙计们!)我设法使用类似这样的方法导入了我的课程:

'stuff/dog.js':

goog.module('canine');
canine.dog = class {
    constructor() {
        …
    }
    addLeg() {
        this.legs++;
    }
}

'stuff/pound.js':

goog.require('canine');
let rex = new canine.Dog();

对我来说并不明显的一件事是命名空间('canine')不需要与类名或文件名/路径有任何关系。

【讨论】:

  • 你的意思是第二个代码 sn-p 中的goog.require('canine'); 吗?是的,命名空间是任意的!但是,如果您愿意,您可以选择直接导出类名(通过执行 goog.module('Dog') 然后 Dog = class {exports = class { 或其他取决于您的设置)。
  • 哎呀,是的。再次感谢!
猜你喜欢
  • 1970-01-01
  • 2016-08-15
  • 2019-09-27
  • 2010-12-14
  • 2014-10-15
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多