UNPKG

@kfl-ui/utils

Version:

Vue 工具集合,包含自动路由生成器

60 lines (59 loc) 2.25 kB
// autoRouter.ts import { createRouter, createWebHistory } from "vue-router"; function createRouterFromGlobs(pages, components, base = "/") { var _a; const normalizePath = (path) => path.replace("/src/views", "").replace(/\/page\.(ts|js)$/, "") || "/"; const getRouteName = (path) => path.split("/").filter(Boolean).join("-") || "index"; const routeMap = {}; const childrenPaths = /* @__PURE__ */ new Set(); for (const [pagePath, config] of Object.entries(pages)) { const routePath = normalizePath(pagePath); const compPath = pagePath.replace(/page\.(ts|js)$/, "index.vue"); const route = { path: routePath, name: getRouteName(routePath), component: components[compPath], meta: config.meta || {}, children: [] }; if (config.redirect) { route.children.push({ path: "", redirect: config.redirect }); } routeMap[routePath] = route; } for (const [pagePath, config] of Object.entries(pages)) { const parentPath = normalizePath(pagePath); if ((_a = config == null ? void 0 : config.children) == null ? void 0 : _a.length) { config.children.forEach((child) => { var _a2, _b; const fullPath = `${parentPath}/${child.path}`.replace(/\/+/g, "/"); const compPath = `/src/views${fullPath}/index.vue`; const childConfig = pages[`/src/views${fullPath}/page.ts`] || pages[`/src/views${fullPath}/page.js`] || {}; const childRoute = { path: child.path, name: child.name, component: components[compPath], meta: child.meta || childConfig.meta || {} }; (_b = (_a2 = routeMap[parentPath]) == null ? void 0 : _a2.children) == null ? void 0 : _b.push(childRoute); childrenPaths.add(`/src/views${fullPath}/page.ts`); childrenPaths.add(`/src/views${fullPath}/page.js`); }); } } const routes = Object.entries(pages).filter(([pagePath]) => !childrenPaths.has(pagePath)).map(([pagePath]) => { const routePath = normalizePath(pagePath); return routeMap[routePath]; }); return createRouter({ history: createWebHistory(base), routes, scrollBehavior: () => ({ top: 0 }) }); } export { createRouterFromGlobs };