一、需求
- 将导入后的文件配置到 Vue 的 router 中,主要配置里面的 path 和 componets 属性。所以,要拿到导入模块的每一个子模块的名字和路径信息。
二、实现代码
const files = require.context("../components/bootstrap", true, /\.vue$/);
const modules = {};
const modulesPath = [];
const children = [];
files.keys().forEach((key, index) => {
modules[key.replace(/(\.\/|\.vue)/g, "")] = files(key).default;
modulesPath.push(key.slice(2, -4).toLowerCase());
const obj = {};
obj.path = modulesPath[index];
for (let item in modules) {
if (item === key.slice(2, -4)) {
obj.component = modules[key.slice(2, -4)];
}
}
children.push(obj);
});
console.log(children);
export default [...children];