如何正确导出节点4中的 ES6类?

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

"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)
....

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

313020 次浏览

使用

// 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

因此出现了错误消息“ Can not set property‘ AspectType’of unDefinition”,因为 module.export === undefined

还有

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

你能写下来吗

class AspectType {
// ...
}

得到本质上相同的行为。

类表达式 可用于简化。

 // 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();

我也有同样的问题。 我发现我把我的接收对象命名为与类名相同的名字。例如:

const AspectType = new AspectType();

把事情搞得一团糟。 希望这能帮上忙

其他几个答案差不多,但说实话,我认为最好使用最简洁、最简单的语法。OP 请求一种在 ES6/ES2015中导出类的方法。我觉得没有比这更干净的了:

'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();