vue3自动注册路由+路由懒加载

565 阅读1分钟

扫描文件夹目录

import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
const routers = [];

const contexts = require.context('@/application', true, /index.vue$/,'lazy');
contexts.keys().forEach(value => {
	const path = value.substring(value.indexOf('/'), value.lastIndexOf('/'));
	//components作为页面内部组件,不注册路由
	if (!path.split('/').includes('components')) {
		const componentLocation = value.substring(value.indexOf('.') + 1);
		const componentName = path.substring(1);
		routers.push({
			path: `/${componentName}`,
			name: componentName,
			component: () => import(`@/application${componentLocation}`)
		});
	}
});

const routes: Array<RouteRecordRaw> = [...routers];

const router = createRouter({
	history: createWebHashHistory(),
	routes
});

export default router;