Node 4でES6クラスを適切にエクスポートするにはどうすればいいですか? 質問する

Node 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 の質問も見ましたが、その解決策を実装しようとすると別のエラー メッセージが表示されます。

ベストアンサー1

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

おすすめ記事