关于vite2与vite3路由批量导入问题Ts版本

关于vite2与vite3路由批量导入问题Ts版本

  • 当在 import.meta.glob 中使用别名(alias)时,键值总是绝对路径。
在vite2中
  • 路由批量导入

import type { RouteRecordRaw } from 'vue-router';
// import type { MenuDataItem } from './typeing';
import commonRoutes from './common';//公共路由
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router';
const modules = import.meta.globEager("./routers/*.ts");
export const routes: RouteRecordRaw[] = [...commonRoutes];
Object.values(modules).forEach(item => routes.push(...item.default));
const router = createRouter({
  history: createWebHashHistory(),
  routes: routes as RouteRecordRaw[],
  scrollBehavior: (to, from) => {
    if (to.path !== from.path) {
      setTimeout(() => {
        const doc = document.getElementById('app');
        if (doc) doc.scrollTop = 0;
      });
    }
    return { top: 0 };
  },
})
export default router;


  • 在上面这个导入中import.meta.globEager方法仅在vite2中使用,在vite3中弃用了

  • 批量导入注册全局组件

  • //在plugins中创建个ts文件


import type { App } from 'vue';
const modulesFiles = import.meta.globEager("@/components/*.vue")
const components: any[] = [];
Object.values(modulesFiles).forEach(item => components.push(item.default));
const install = (app: App) => components.forEach(item => app.component(item['__name'], item))



//这种方式导出有个好处就是,可以在main.ts文件中直接使用app.use()包裹一下即可
export default { install };
  • //在main.ts中



import install from '@/plugins/components/index'


const app = createApp(App);
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
const arr = [pinia, router, Toast, Dialog, Notify, ImagePreview,];
arr.forEach(item => app.use(item))
//这里
app.use(install)
app.mount('#app');

  • 文件层级关系如下
  • 批量导入路由文件层级关系
在vite3
  • 批量导入使用
import.meta.glob('*', { eager: true })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值