如何在 Node 4 中正确导出 ES6 class?

How to properly export an ES6 class in Node 4?

我在模块中定义了一个class:

"use strict";

var AspectTypeModule = function() {};
module.exports = AspectTypeModule;

var AspectType = class AspectType {
    // ...    
};

module.export.AspectType = AspectType;

但我收到以下错误消息:

TypeError: Cannot set property 'AspectType' of undefined
    at Object.<anonymous> (...\AspectType.js:30:26)
    at Module._compile (module.js:434:26)
    ....

我应该如何导出这个 class 并在另一个模块中使用它?我看到了其他 SO 问题,但是当我尝试实施他们的解决方案时收到其他错误消息。

使用

// aspect-type.js
class AspectType {

}

export default AspectType;

然后导入它

// some-other-file.js
import AspectType from './aspect-type';

阅读http://babeljs.io/docs/learn-es2015/#modules了解更多详情

如果您在 Node 4 中使用 ES6,则不能在没有转译器的情况下使用 ES6 模块语法,但 CommonJS 模块(Node 的标准模块)工作方式相同。

module.export.AspectType

应该是

module.exports.AspectType

因此出现错误消息 "Cannot set property 'AspectType' of undefined" 因为 module.export === undefined.

此外,对于

var AspectType = class AspectType {
    // ...    
};

你能写吗

class AspectType {
    // ...    
}

并获得基本相同的行为。

class expression可以简单用

 // Foo.js
'use strict';

// export default class Foo {}
module.exports = class Foo {}

-

// main.js
'use strict';

const Foo = require('./Foo.js');

let Bar = new class extends Foo {
  constructor() {
    super();
    this.name = 'bar';
  }
}

console.log(Bar.name);
// person.js
'use strict';

module.exports = class Person {
   constructor(firstName, lastName) {
       this.firstName = firstName;
       this.lastName = lastName;
   }

   display() {
       console.log(this.firstName + " " + this.lastName);
   }
}

// index.js
'use strict';

var Person = require('./person.js');

var someone = new Person("First name", "Last name");
someone.display();

我遇到了同样的问题。 我发现我将我的接收对象命名为与 class 名称相同的名称。示例:

const AspectType = new AspectType();

这把事情搞砸了...... 希望这有帮助

其他几个答案很接近,但老实说,我认为您最好使用最简洁、最简单的语法。 OP 请求一种在 ES6 / ES2015 中导出 class 的方法。我认为没有比这更干净的了:

'use strict';

export default class ClassName {
  constructor () {
  }
}

有时我需要在一个文件中声明多个 类,或者我想导出基础 类 并保留它们的名称导出,因为我的 JetBrains 编辑器更了解这一点。我只是用

global.MyClass = class MyClass { ... };

还有其他地方:

require('baseclasses.js');
class MySubclass extends MyClass() { ... }

我就这么写了

在 AspectType 文件中:

class AspectType {
  //blah blah
}
module.exports = AspectType;

并像这样导入它:

const AspectType = require('./AspectType');
var aspectType = new AspectType;

使用 ECMAScript 2015,您可以像这样导出和导入多个 类

class Person
{
    constructor()
    {
        this.type = "Person";
    }
}

class Animal{
    constructor()
    {
        this.type = "Animal";
    }
}

module.exports = {
    Person,
    Animal
};

然后你在哪里使用它们:

const { Animal, Person } = require("classes");

const animal = new Animal();
const person = new Person();

如果出现名称冲突,或者您更喜欢其他名称,您可以像这样重命名它们:

const { Animal : OtherAnimal, Person : OtherPerson} = require("./classes");

const animal = new OtherAnimal();
const person = new OtherPerson();