我应该在每个文件中需要一个模块还是需要一次并将其作为parameter passing?

比方说,我有50个模块,每个需要Underscore库。 加载下划线50次更好吗?

//a module var _ = require('underscore'); 

或者最好从主文件传递它:

 //app.js var _ = require('underscore'); require('./app_modules/module1.js')(_); // passing _ as argument require('./app_modules/module2.js')(_); // passing _ as argument require('./app_modules/module3.js')(_); // passing _ as argument (..) 

它有什么区别?

模块在第一次被加载后被caching,所以你可以在每个文件中要求它就好了。 require()调用Module._load

 Module._load = function(request, parent, isMain) { // 1. Check Module._cache for the cached module. // 2. Create a new Module instance if cache is empty. // 3. Save it to the cache. // 4. Call module.load() with your the given filename. // This will call module.compile() after reading the file contents. // 5. If there was an error loading/parsing the file, // delete the bad module from the cache // 6. return module.exports }; 

请参阅: http : //fredkschott.com/post/2014/06/require-and-the-module-system/

第一个选项通常是最好的。

由于需求被caching,所以select第二个选项没有提高性能。 使用第一个选项的优点是更容易理解,并且不需要使每个模块都以Underscore库作为参数的行为。

但是,您可能希望能够轻松更改正在使用的库。 如果是这样的话,第二种select是有道理的,因为你只需要改变主文件中的库。 无论如何,我相信这是用例并不普遍,所以可能你使用第一个选项是很好的。