如何在node项目中使用babel编译的class?

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

这是我正在测试的用 es2015 编写的非常简单的 class:

"use strict";

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

export default Car;

我使用 babel-cli 转译 class 所以它可以在节点中使用...这是输出:

"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;

在我的节点项目中,我像这样包含该模块:

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

但是当我执行以下操作时,出现 "Car is not a function" 错误:

var blueCar = new Car('blue');

我是 运行 node v5.8 在这种情况下是否有所不同?

1) 您可以 import 默认从 ES 中的模块转译它们:

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

2) 您可以导出 Car class、转译和 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');