Seanonymous
Seanonymous

Reputation: 1374

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

Upvotes: 2

Views: 759

Answers (2)

Seanonymous
Seanonymous

Reputation: 1374

Using the answers from Jeremy and Chad (thanks, guys!) I managed to get my class imported using something similar to this:

'stuff/dog.js':

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

'stuff/pound.js':

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

One thing that wasn't obvious to me is that the namespace ('canine') doesn't need to have anything to do with the class name or filename/path.

Upvotes: 1

Chad Killingsworth
Chad Killingsworth

Reputation: 14411

ES6 classes can be assigned to namespaces:

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

Upvotes: 1

Related Questions