如何在节点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) .... 
我应该如何导出这个类并在另一个模块中使用它? 我已经看到其他的问题,但是当我尝试实现他们的解决scheme时,我收到了其他的错误信息。
如果在节点4中使用ES6,则不能在没有转换器的情况下使用ES6模块语法,但CommonJS模块(节点的标准模块)工作原理相同。
 module.export.AspectType 
应该
 module.exports.AspectType 
 因此错误消息“Can not set property AspectType of undefined”,因为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(); 
类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); 
其他几个答案都接近了,但说实话,我认为你最好用最简洁,最简单的语法。 OP要求在ES6 / ES2015中出口一个class级。 我不认为你能比这更清洁:
 'use strict'; export default class ClassName { constructor () { } } 
使用
 // aspect-type.js class AspectType { } export default AspectType; 
然后导入它
 // some-other-file.js import AspectType from './aspect-type'; 
我有同样的问题。 我发现我叫我的接收对象与class级名称相同的名称。 例:
 const AspectType = new AspectType(); 
这样搞砸了…希望这有助于
有时候我需要在一个文件中声明多个类,或者我想导出基类并保留它们的名称,因为我的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;