一次性导入所有文件,并配置到路由中

78 阅读1分钟

一、需求

  • 将某目录中的文件一次性导入
image.png
  • 将导入后的文件配置到 Vue 的 router 中,主要配置里面的 path 和 componets 属性。所以,要拿到导入模块的每一个子模块的名字和路径信息。
image.png

二、实现代码

// 导入所有目录所有文件,第一个参数是路径,第二个参数控制是否遍历子目录,第三个参数指文件类型
// 可打印 files.key() 查看详情
const files = require.context("../components/bootstrap", true, /\.vue$/);
// 存储所有导入的模块
const modules = {};
// 存储所有的路由配置中的 path
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];