感谢@splintor(谢谢)。
但这里是我自己的衍生版本。
好处:
- 哪些模块导出收集在
{module_name: exports_obj} 对象下。
-
module_name 是根据其文件名构建的。
- ...没有扩展名并用下划线替换斜杠(在子目录扫描的情况下)。
- 添加了 cmets 以简化自定义。
- 即您可能不想在子目录中包含文件,例如,如果 root 级别 模块手动需要这些文件。
编辑:如果像我一样,您确定您的模块除了(至少在根级别)常规 javascript 对象外不会返回任何其他内容,那么您
还可以“挂载”它们以复制其原始目录结构
(参见末尾的代码(深度版)部分)。
代码(原版):
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
));
示例:
最终console.log(allModules); 的示例输出:
{
main: { title: 'Webpack Express Playground' },
views_home: {
greeting: 'Welcome to Something!!',
title: 'Webpack Express Playground'
}
}
目录树:
models
├── main.js
└── views
└── home.js
代码(深度版):
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
));
示例:
使用此版本的上一个示例的结果:
{
main: { title: 'Webpack Express Playground' },
views: {
home: {
greeting: 'Welcome to Something!!',
title: 'Webpack Express Playground'
}
}
}