Javascript Node.js ES6 如何从模块导出类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37395114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:16:43  来源:igfitidea点击:

Node.js ES6 how to export class from module?

javascriptnode.jsecmascript-6commonjs

提问by kubal5003

I'm trying to export an ES6 class from a CommonJS module in Node.js 6.2.0

我正在尝试从 Node.js 6.2.0 中的 CommonJS 模块导出 ES6 类

class MyClass{
    //class contents here
}

exports = MyClass;

Then import it in another module:

然后将其导入另一个模块:

var MyClass = require('/path/to/module.js')
var instance = new MyClass();

However I'm getting the following exception:

但是我收到以下异常:

TypeError: MyClass is not a constructor

How can I properly do it?

我怎样才能正确地做到这一点?

Please note that I'm not using Babel/Tranceur it's pure JS as implemented in the latest Node 6.2.0 which according to Kangax implements ES6 in 93%.

请注意,我没有使用 Babel/Tranceur,它是在最新的 Node 6.2.0 中实现的纯 JS,根据 Kangax,它在 93% 中实现了 ES6。

//Edit: this is not a problem with exports vs module.exports. While using exports alone I'm getting some object with __proto__set.

//编辑:这不是exports vs module.exports的问题。单独使用导出时,我得到了一些带有__proto__set 的对象。

回答by Bergi

You will need to assign to module.exports, not the local exportsvariable.

您需要分配给module.exports,而不是局部exports变量。