Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I require a module in every file or require it once and pass it as argument?

Lets say I have 50 modules and each needs Underscore library. Is it better to load Underscore like that 50 times:

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

or its better to pass it from main file:

//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
(..)

Does it make any difference?

like image 825
youbetternot Avatar asked Jan 14 '15 17:01

youbetternot


1 Answers

The module is cached after it is loaded the first time, so you can require it in every file just fine. require() calls 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
};

see: http://fredkschott.com/post/2014/06/require-and-the-module-system/

like image 112
Wex Avatar answered Oct 11 '22 06:10

Wex