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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With