在Node.JS中为类导出语句

节点目前在严格模式下启用class级build设。

如果我有以下class级:

"use strict" class MyClass { constructor(foo) { this.foo = foo } func(){/*ETC */} } 

什么是相应的导出语句可以导出到另一个模块。 怎么样从另一个文件的import声明?

使用commonJS requiremodule.exports ,您现在可以“导入”或“导出”当前在节点中的其他任何东西。

Foo.js

 class Foo {} module.exports = Foo // or if you want to edit additional objects: // module.exports.Foo = Foo // module.exports.theNumberThree = 3 

Bar.js

 var Foo = require("./Foo") var foo = new Foo() 

这是多less节点支持ES6模块真的是一个问题。 虽然目前允许使用类,但是ES6的导入/导出function尚未实现,更多地依赖于CommonJS的要求。

要导出使用以下内容:

 //MyClass.js class MyClass { constructor(foo) { this.foo = foo } func(){/*ETC */} } module.exports = function(foo){ return new MyObject(foo); } 

导入:

 //in app.js var myClass = require('./MyClass'); var mc = new myClass(foo);