繁体   English   中英

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

[英]How to properly export an ES6 class in Node 4?

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

"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问题,但是当我尝试实现它们的解决方案时却收到其他错误消息。

如果在节点4中使用ES6,则必须在没有编译器的情况下才能使用ES6模块语法,但是CommonJS模块(节点的标准模块)的工作原理相同。

module.export.AspectType

应该

module.exports.AspectType

因此出现错误消息“无法设置未定义的属性'AspectType'”,因为module.export === undefined

另外,对于

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

你能写吗

class AspectType {
    // ...    
}

并获得基本相同的行为。

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

使用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();

使用

// aspect-type.js
class AspectType {

}

export default AspectType;

然后导入

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

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

类表达式可以简化使用。

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

我只是这样写

在AspectType文件中:

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

并像这样导入它:

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

其他几个答案也差不多了,但老实说,我认为最好使用最干净,最简单的语法。 OP要求在ES6 / ES2015中导出类的方法。 我认为您不会比这更干净:

'use strict';

export default class ClassName {
  constructor () {
  }
}

我有同样的问题。 我发现我将接收对象称为类名。 例:

const AspectType = new AspectType();

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

有时我需要在一个文件中声明多个类,或者由于我的JetBrains编辑器更了解这一点,所以我想导出基类并保持其名称被导出。 我只是用

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

还有其他地方:

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

暂无
暂无

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

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