Search code examples
javascriptecmascript-6google-closure-compiler

Include an Ecmascript 6 class using Google Closure Compiler?


How do I include an Ecmascript 6 class when using Google Closure Compiler?

E.g., I have a class in 'stuff/dog.js':

class dog {
    constructor() {
        …
    }
    addLeg() {
        this.legs++;
    }
}

And I want to include it in 'stuff/pound.js' so I can write:

let rex = new Dog();

How should this be handled? I can't use stuff.dog as a class name so passing the calls to goog.provide() doesn't seem to be an option.

Thanks for any help!

Edit: Using the latest (20160517 1.0) version of Closure Compiler, this can be handled with plain 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() );
    }
}

Though it does give me a warning for some reason: Closure Compiler warns "Bad type annotation. Unknown type …" when Ecmascript 6 class is extended


Solution

  • ES6 classes can be assigned to namespaces:

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