node.js:以任何方式导出文件中的所有函数(例如,启用unit testing),一个接一个

在node.js中,是否有任何快捷方式导出给定文件中的所有function? 我想做unit testing的目的,因为我的unit testing是从我的生产代码单独的文件。

我知道我可以通过手动导出每个function,如下所示:

exports.myFunction = myFunction; 

但是,我想知道是否有一个更简单/闪烁的方式来做到这一点。

(是的,我意识到模块化的原因,并不总是一个好主意,出口的所有function,但unit testing的目的,你确实希望看到所有的小function,所以你可以逐件testing)。

谢谢!

你可以做这样的事情:

 // save this into a variable, so it can be used reliably in other contexts var self = this; // the scope of the file is the `exports` object, so `this === self === exports` self.fnName = function () { ... } // call it the same way self.fnName(); 

或这个:

 // You can declare your exported functions here var file = module.exports = { fn1: function () { // do stuff... }, fn2: function () { // do stuff... } } // and use them like this in the file as well file.fn1(); 

或这个:

 // each function is declared like this. Have to watch for typeos, as we're typing fnName twice fnName = exports.fnName = function () { ... } // now you can use them as file-scoped functions, rather than as properties of an object fnName(); 

Mixin对象是答案。

这个lib可以帮助你: https : //github.com/shimondoodkin/nodejs-clone-extend

 //file1.js var _ = require('cloneextend'); _.extend(this, require('file2.js')); 

现在file1.js全部从file2.js导出

这是一个简单的方法来做到这一点。 parsingAST并查找顶级函数定义,然后导出这些定义。

 const esprima = require('esprima') const program = fs.readFileSync(__filename,'utf8') const parsed = esprima.parseScript(program) for (let fn of parsed.body) { if (fn.type.endsWith('FunctionDeclaration')) { module.exports[fn.id.name] = eval(fn.id.name) } }