vue 路由中 vite 与webpack 动态 导入的方法汇总

vite 动态导入路由:

router/index.js文件

javascript 复制代码
//vite 下面寻找 views 文件夹下面所有的page.js文件
let pageList = import.meta.glob('../views/**/page.json', {
  eager: true,
  import: 'default',
});
//所有的文件
const modules = import.meta.glob('../views/**/**.vue');

//遍历
let pages = Object.entries(pageList).map(([path, meta]) => {
  let pathName = path.slice(8, -10);
  let name = pathName.slice(1).split('/').join('-');
  let fileName = path.slice(0, -10);
  let fixFileName = fileName.split('/').pop();
  let filePath = fileName + '/' + fixFileName + '.vue';

  return {
    path: pathName,
    name: name,
    component: modules[filePath],
    meta,
  };
});

 routes: [
    {
      path: '/',
      name: 'layout',
      redirect: '/home',
      component: () => import('../components/layout/layout.vue'),
      meta: {
        title: '首页',
      },
      children: pages,
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login.vue'),
      meta: {
        title: '登录',
      },
    },
  ],

以下是 截图:

这个是webpack 动态导入路由:

javascript 复制代码
//读取配置文件
const context = require.context('../components/page', true, /\.json$/);
//读取路由文件
const contextVue = require.context('../components/page', true, /\.vue$/);

let fileObj = {};
//动态读取文件
contextVue.keys().map(key => {
    let keyName = key.slice(1);
    fileObj[keyName] = contextVue(key).default;
});

let routerPathArr = [];
//动态配置路由
context.keys().forEach(key => {
    let obj = context(key);
    let compKey = obj['componentPath'];
    let routeObj = {
        path: obj['path'],
        name: obj['name'],
        component: fileObj[compKey],
        meta: obj['meta']
    };
    routerPathArr.push(routeObj);
});

以下是截图:

相关推荐
开开心心就好4 小时前
批量提取PDF中的图片,直接导出原图
前端·javascript·支持向量机·智能手机·pdf·html·启发式算法
Setsuna_F_Seiei6 小时前
前端转型 Agent 开发 05 之 Agent Hooks 与 Checkpointer(让 Agent 从全自动转变人为可掌控)
前端·agent·ai编程
百万蹄蹄向前冲8 小时前
风扇转了一晚上MVP专家团翻车事故
前端·人工智能
默_笙8 小时前
🏛 给 AI 配一间办公室:Harness Engineering 六大模块与它的实现
前端·javascript
linux_cfan10 小时前
videojs v10 源代码系列解读:14 · 谓词守卫:在运行时安全地调用能力
前端·javascript·音视频
kyriewen10 小时前
我扒了 10,221 条 JD:腾讯技术岗 75% 在要 AI
前端·人工智能·ai编程
郑州光合科技余经理11 小时前
同城外卖小程序开发:下单成功后,后台导出能不能对上用户端状态
开发语言·前端·git·后端·uni-app·php·ai编程
+VX:Fegn089511 小时前
计算机毕业设计|基于springboot + vue旅游管理系统(源码+数据库+文档)
java·开发语言·vue.js·spring boot·课程设计
雪芽蓝域zzs11 小时前
第 7 章:双 Y 轴组合图(柱状 + 折线,看板高频场景)
vue.js·echars
IT_陈寒12 小时前
Vue的响应式让我熬到凌晨三点,原来漏了这个小细节
前端·人工智能·后端