关于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 })