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

使用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")

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
            modules[/* @vite-ignore */ `../views/${itemRouter.component}`],
        })
      }
      if (itemRouter.children && itemRouter.children.length) {
        routerPackag(itemRouter.children)
      }
      return true
    })
  }
}
  • 12
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值