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

Let's say I have 50 modules, and each of them needs a subtree library. Is it better to download Underscore like this 50 times:

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

or better pass it from the 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
(..)

What is the difference?

+4
source share
2 answers

The module is cached after loading it for the first time, so you can require it in every file just fine. require()causes 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/

+3
source

The first option is usually the best.

, , . , Underscore .

, . , , . , , , , , .

0

All Articles