简体   繁体   English

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

[英]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:这是我正在测试的一个用 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:我使用 babel-cli 转译该类,以便它可以在节点中使用......这是输出:

"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?如果在这种情况下有所不同,我正在运行 node v5.8?

1) You can import default from module in ES and transpile them: 1) 您可以从 ES 中的模块中import default 并对其进行转译:

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

2) You can export Car class, transpile and require : 2) 您可以导出Car类、转译和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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM