2016-09-11 39 views
0

在1个module.export中包含许多方法和模块中的每个函数的module.export之间是否有不同的效率?1 module.exports与module.exports为每个功能?

module.exports={ 
func1: function (req, res, next) {}, 
func2: function (req, res, next) {} 
} 

module.exports.func1 = function(){}; 
module.exports.funct2 = function(){}; 

我被告知,以调查是否有2个选项之间的差异。 比其他方式更好吗? 谢谢。

回答

0

除了第一个将导出多个函数,而第二个将逐个导出之外,上述两者之间没有区别。当你需要在另一个模块中返回相同的对象。还有另一种导出模块的方法,称为单值导出,与您提到的不同。

module.exports = function() { ··· }; 
0

实际上,没有区别。在CommonJS中,module.exports只是另一个对象。这两个样本都会导出与该对象上的键相同的功能。

唯一真正的区别在于,第一个示例完全重新指定module.exports对象,而在第二个示例中,您只是将值分配给键。在任何理智的用例中,这根本就不重要。

在节点,第二示例可以缩写为

exports.func1 = function() {}; 
exports.func2 = function() {}; 

第一种形式可以被用来导出一个默认值和一些互补值,这实际上是一个相当普遍的图案。考虑以下几点:

function express() {} 
function Router() {} 

module.exports = express 
module.exports.Router = Router 

这将允许您通过

var express = require('express') 
var Router = express.Router 

进口快件虽然稍微偏离主题了这个问题,ES6类似物是这样的:

export const func1 = function() {} 
export const func2 = function() {} 

export { 
    func1, 
    func2 
}