It is possible to var x = require('x.js')
and use x
later on to access all the nice stuff. What is the closest way to build an array of required things, like:
var xs = [require('a.js'), require('b.js')]
and then access the exported features as xs[0].feature
and xs[1].feature
?
It is possible to var x = require('x.js')
and use x
later on to access all the nice stuff. What is the closest way to build an array of required things, like:
var xs = [require('a.js'), require('b.js')]
and then access the exported features as xs[0].feature
and xs[1].feature
?
require
an array of things.
– alisianoi
Commented
Jul 3, 2016 at 22:10
Unless you have very good reason to do this, it should probably be avoided. But it can be done quite simply using Array.prototype.map()
.
var xs = ['foo.js', 'bar.js', 'baz.js'].map(require);
Perhaps you can do something like this:
var x = [];
var requiredLibraries = ['a.js', 'b.js', 'c.js'];
requiredLibraries.forEach(function(element, index, array) {
x.push(require(element));
});
EDIT Please note that I don't think this is a good idea, because of confusion it might bring and lower the readability of your code, if nothing else.
Both getRoutes and postRoutes are files .js (getRoutes.js and postRoutes.js)
I used this approach to create an index.js with all my routes.
index.js
const routes = [require("./getRoutes"), require("./postRoutes")];
module.exports = { routes };
// OR
const routes = ["./getRoutes", "./postRoutes"].map(require);
module.exports = { routes };
getRoutes.js and postRoutes.js they would look something like that
const express = require("express");
const router = express.Router();
const { users } = require("../controllers");
router.post("/user", users);
module.exports = router;