我是否应该在每个文件中都需要一个模块或者需要它一次并将其作为参数传递?

you*_*not 6 javascript node.js

假设我有50个模块,每个模块都需要Underscore库.是否更好地加载像这样50次的Underscore:

//a module
var _ = require('underscore');
Run Code Online (Sandbox Code Playgroud)

或者更好地从主文件传递它:

//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
(..)
Run Code Online (Sandbox Code Playgroud)

它有什么不同吗?

Wex*_*Wex 5

该模块在第一次加载后被缓存,因此您可以在每个文件中都要求它.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
};
Run Code Online (Sandbox Code Playgroud)

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