All merits to @splintor (thanks).
But here it is my own derived version.
Benefits:
- What modules export is gathered under a
{module_name: exports_obj}
object.
- module_name is build from its file name.
- ...without extension and replacing slashes by underscores (in case of subdirectory scanning).
- Added comments to ease customization.
- I.e. you may want to not include files in subdirectories if, say, they are there to be manually required for root level modules.
EDIT: If, like me, you're sure your modules won't return anything else than (at least at root level) a regular javascript object, you
can also "mount" them replicating their original directory structure
(see Code (Deep Version) section at the end).
Code (Original Version):
function requireAll(r) {
return Object.fromEntries(
r.keys().map(function(mpath, ...args) {
const result = r(mpath, ...args);
const name = mpath
.replace(/(?:^[.\/]*\/|\.[^.]+$)/g, '') // Trim
.replace(/\//g, '_') // Relace '/'s by '_'s
;
return [name, result];
})
);
};
const allModules = requireAll(require.context(
// Any kind of variables cannot be used here
'@models' // (Webpack based) path
, true // Use subdirectories
, /\.js$/ // File name pattern
));
Example:
Sample output for eventual console.log(allModules);
:
{
main: { title: 'Webpack Express Playground' },
views_home: {
greeting: 'Welcome to Something!!',
title: 'Webpack Express Playground'
}
}
Directory tree:
models
├── main.js
└── views
└── home.js
Code (Deep Version):
function jsonSet(target, path, value) {
let current = target;
path = [...path]; // Detach
const item = path.pop();
path.forEach(function(key) {
(current[key] || (current[key] = {}));
current = current[key];
});
current[item] = value;
return target;
};
function requireAll(r) {
const gather = {};
r.keys().forEach(function(mpath, ...args) {
const result = r(mpath, ...args);
const path = mpath
.replace(/(?:^[.\/]*\/|\.[^.]+$)/g, '') // Trim
.split('/')
;
jsonSet(gather, path, result);
});
return gather;
};
const models = requireAll(require.context(
// Any kind of variables cannot be used here
'@models' // (Webpack based) path
, true // Use subdirectories
, /\.js$/ // File name pattern
));
Example:
Result of previous example using this version:
{
main: { title: 'Webpack Express Playground' },
views: {
home: {
greeting: 'Welcome to Something!!',
title: 'Webpack Express Playground'
}
}
}