2016-09-11 41 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 
}