Reputation: 11447
I understand that one can pass variables to a module by exporting modules as a function with parameters for each variable you wish to pass. E.g.
module.exports = module.exports = function (injectedVariable) {
app.get('/whatever', function (req, res, next) {
// Do something with injectedVariable
});
};
I understand that this is useful for passing variables like "app" around different modules. However, what is the preferred pattern for dealing with external package dependencies. I've seen code like this.
App.js
var jquery = require('jquery');
var _ = require('underscore');
var backbone = require('backbone');
var express = require('express');
// Pretty much every other external library
var app = express();
// Code here might config some of the 3rd party modules
require('routes/main.js')(app, _, jquery, backbone, someOtherModule, someOtherModule2);
require('routes/main.js')(app, _, jquery, backbone, someOtherModule, someOtherModule2);
// Etc
// Init server etc
And then each route module will export a function with all the paramaters available to support the packages it needs being passed to them.
Is there any reason for doing this? Would it not be cleaner to just require('whatever') at the top of each file? Presumably, having many require()'s for the same module across different files isn't a problem as node will then just pull out its cached version stored from the first instance of require() it encountered at runtime. Which method of managing package dependencies is preferred?
Upvotes: -1
Views: 932
Reputation: 146074
Is there any reason for doing this?
Using this pattern for regular modules like underscore, jquery, backbone, is blatant violation of the basic CommonJS pattern upon which node is built. Don't do it. Just require your modules directly using CommonJS syntax. For testing and dependency injection, there are CommonJS-compatible ways to do that such as rewire or injectr.
However, it's different with the express app
instance as that is a specific object with a certain configuration, so it's OK to pass that in. However, express 4 eliminates the most common need to use this pattern since you can mount subapplications in an outer main application.
Upvotes: 1