Do I really have to repeat all this requirement in every route module file?

I am building a larger web application and have now begun to understand the use of modular routes in my files. But when I do this, I notice that I need to rewrite a lot of requirements ... Before I started sorting through the routes to my own file, I had about 20 required modules in my main application, processing everything from the database to emails .. .

Many of these modules are used on most routes ... which means that I should repeat maybe 15-20 requirements in each file of the route module.

Question: This seems like a lot of repetitive code, but maybe this is the best way to do this?

At least official NPMs work this way.

+4
source share
1 answer

You can write a module (say, common.js) that would requirefulfill all your requirements and return a single object:

module.exports = {
  http:        require('http'),
  request:     require('request'),
  async:       require('async'),
  someModule:  require('./someModule')
};

Then all you have to do is requireone module common:

var common = require('./common');
common.request.get(...);
common.async.parallel(...);

The only inconvenience is that now you need to write common.when you want to access these modules.

You can also use global variables . In fact, using global variables is bad practice, and it is highly recommended that you not use them:
Why are global variables considered bad practice? (node.js)
Why are globals bad?

+4

All Articles