ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

vite 使用import.meta.glob动态添加vue页面

2021-08-11 11:01:41  阅读:1124  来源: 互联网

标签:vue views component glob itemRouter meta import vite


使用vite的 GlobImport 动态导入多个vue页面

在使用vite实现后台管理系统的时候,有个需求是动态导入views文件夹下面的所有页面,在vite1.0版本的时候只能手动写映射关系,升级到vite2.0之后,在本地使用没有问题,打包上生产直接裂开~~,vite提供了一个Glob Import方法。

如果直接使用import.meta.glob,vscode会报类型ImportMeta上不存在属性“glob”的错误,需要在tsconfig文件下添加类型定义vite/client

{
  "compilerOptions": {
    "types": ["vite/client"]
  }
}

之前的代码如下:

//routes
 {
    path: "/login",
    name: "login",
    component: () => import("/@views/system/login/index.vue"),
  },

使用Glob Import改写代码 动态添加

//引入所有views下.vue文件
const modules = import.meta.glob("../views/**/**.vue")
//使用modules
export const routerPackag = function (routers: any) {
  if (routers) {
    routers.filter((itemRouter: any) => {
      if (itemRouter.component != "Layout") {
        router.addRoute("home", {
          path: `${itemRouter.path}`,
          name: itemRouter.name,
          meta: {
            title: itemRouter.name,
          },
          component:
            // import(/* @vite-ignore */ `/@views/${itemRouter.component}`),
            modules[/* @vite-ignore */ `../views/${itemRouter.component}`],
        })
      }
      if (itemRouter.children && itemRouter.children.length) {
        routerPackag(itemRouter.children)
      }
      return true
    })
  }
}

标签:vue,views,component,glob,itemRouter,meta,import,vite
来源: https://blog.csdn.net/qq1161839630/article/details/119598248

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有