Search code examples
node.jsecmascript-6babeljstranspiler

How do I use a class compiled by babel in a node project?


Here is a very simple class that I'm testing written in es2015:

"use strict";

class Car {
    constructor(color) {
        this.color = color;
    }
}

export default Car;

I use babel-cli to transpile that class so it can be used in node...this is the output:

"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Car = function Car(color) {
    _classCallCheck(this, Car);

    this.color = color;
};

exports.default = Car;

In my node project I include that module like this:

var Car = require("js-models/lib/Car");

But when I do the following I get a "Car is not a function" error:

var blueCar = new Car('blue');

I'm running node v5.8 if that makes a difference in this case?


Solution

  • 1) You can import default from module in ES and transpile them:

    import Car from 'js-models/lib/Car';
    let blueCar = new Car('blue');
    

    2) You can export Car class, transpile and require:

    // module js-models/lib/Car
    "use strict";
    
    export class Car {
        constructor(color) {
            this.color = color;
        }
    }
    
    // node project
    var Car = require("js-models/lib/Car").Car;    
    var blueCar = new Car('blue');