nathasm
nathasm

Reputation: 2574

Using babeljs compiled files with existing project

I have a simple class that is written in ES6

class MyClass {
  constructor() {
    this.firstVar = 'a';
    this.secondVar = 'b';
  }
  get first() { return this.firstVar; }
  set first(val) { this.firstVar = val; }

  get second() { return this.secondVar; }
  set second(val) { this.secondVar = val; }

  allValues() {
    return this.firstVar + this.secondVar;
  }
}

export { MyClass };

I compile that code to ES5 via babel MyClass.es6 > MyClass.js and then try to use it in my existing ES5 codebase:

var t = require('./MyClass');
console.log(t.allValues());

But I get an error stating that t has no method allValues. Is what I'm trying to do possible?

Upvotes: 1

Views: 291

Answers (1)

Felix Kling
Felix Kling

Reputation: 816780

Classes have to be instantiated. You are never creating an instance of MyClass. You are also importing it incorrectly. You are exporting MyClass as a named export and have to import it as such.

In its current form, you would have to do

var MyClass = require('./MyClass').MyClass;
var t = new MyClass();
console.log(t.allValues());

Or you can export it as default export:

export default MyClass;

In which case you can do

var t = require('./MyClass');

(at least with Babel)

Upvotes: 3

Related Questions