javascript - 如何在 Node 4 中正确导出 ES6 类?

标签 javascript node.js module export

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

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

最佳答案

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

关于javascript - 如何在 Node 4 中正确导出 ES6 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32657516/

相关文章:

Python导入错误: No module named pybluez

perl - 用于神经网络的易于使用的 Perl 模块

javascript - 禁用 jqgrid 的编辑(添加、编辑和删除)按钮而不是隐藏(默认行为)

javascript - Aurelia 中的图像源绑定(bind)

javascript - 使用 .split() 将字符串转换为数组(需要改进)

node.js - PencilBlue 在注册表单中添加新字段

node.js - Node + Express : loadtest causing the application to quit with Error: accept ENFILE

node.js - 为不同的git分支创建特定的node_modules目录

PowerShell 在运行 Import-Module 时忽略 Write-Verbose

javascript - 通过函数了解 ES6 中的 Yield