reduce a lot of require() function

112 views Asked by At

I have a lot of CommonJS modules and I need to add all of them to array. Therefore, I have a huge repeated code:

//Container module
var module1 = require('module1'),
    module2 = require('module2'),
 ...
    module25 = require('module25')

var container = [];
container.push(module1);
container.push(module2);
...
container.push(module25);

module.exports = container;

Is it possible to reduce this code? I don't want to make them globaly. I see only only solution, it's inject container inside each module, but I don't want my modules know about container.

1

There are 1 answers

2
Marko Gresak On BEST ANSWER

If I understand your problem correctly, you wish to export an array of modules and get access to that array, i.e. require, somewhere else. If this is correct, you could do something like this:

// requires-file
module.exports = [
    require('module1'),
    require('module2'),
    // ...
];

Or a more functional programming approach, this would appeal more to me, but people prefer different styles:

module.exports = ['module1', 'module2', /*...*/].map(function(m) {return require(m);});

And where you need the files, you can use:

// other-file
var container = require('/requires-file');