import { createRouter, createWebHistory, RouterView } from 'vue-router' import type { RouteRecordRaw } from 'vue-router' import { getToken } from '@/utils/auth' import Layout from '@/layout/index.vue' import { usePermissionStore } from '@/stores/modules/permission' import { h } from 'vue' import { componentMap } from './map' /** 供动态菜单兜底:Vite 不允许 `import(\`@/views/${多段路径}.vue\`)`,用 glob 在构建期收集全部页面 */ const viewModules = import.meta.glob('@/views/**/*.vue') as Record< string, () => Promise<{ default: object }> > function resolveViewFromGlob(componentPath: string) { let rel = componentPath.replace(/\\/g, '/').trim() if (rel.startsWith('@/views/')) rel = rel.slice('@/views/'.length) if (rel.startsWith('/')) rel = rel.slice(1) if (rel.toLowerCase().endsWith('.vue')) rel = rel.slice(0, -4) const candidates = [`/views/${rel}.vue`, `/views/${rel}/index.vue`] for (const target of candidates) { const key = Object.keys(viewModules).find((k) => k.replace(/\\/g, '/').endsWith(target)) if (key) return viewModules[key] } return undefined } function buildInferredComponentPaths(menu: any, parentName?: string) { const parentKey = parentName ? String(parentName).replace(/_Child$/, '').toLowerCase() : '' const menuPath = String(menu.path || '').replace(/^\//, '') const candidates: string[] = [] if (parentKey && menuPath) { candidates.push(`${parentKey}/${menuPath}/index`, `${parentKey}/${menuPath}`) } if (menuPath) { candidates.push(`${menuPath}/index`, menuPath) } return candidates } function findComponentLoader(componentPath: string) { if (componentMap[componentPath]) { return componentMap[componentPath] } const fromGlob = resolveViewFromGlob(componentPath) if (fromGlob) { return fromGlob } // 处理常见的目录结构,例如 'warehouse' -> 'warehouse/index.vue'(变量仅一段,Vite 可分析) if (!componentPath.includes('/')) { return () => import(`@/views/${componentPath}/index.vue`).catch(() => import(`@/views/${componentPath}.vue`)) } return undefined } /** * 空白父级路由组件 */ const ParentView = { name: 'ParentView', render: () => h(RouterView) } /** * 基础路由 - 固定不变的路由 */ export const constantRoutes: RouteRecordRaw[] = [ { path: '/redirect', component: Layout, meta: { hidden: true }, children: [ { path: '/redirect/:path(.*)', component: () => import('@/views/redirect/index.vue') } ] }, { path: '/login', name: 'Login', component: () => import('@/views/login/index.vue'), meta: { title: '登录', hidden: true } }, { path: '/admin/land', name: 'AdminLand', component: () => import('@/views/admin/land/index.vue'), meta: { title: '语言翻译', hidden: true } }, { path: '/', component: Layout, redirect: '/dashboard', children: [ { path: 'dashboard', name: 'Dashboard', component: () => import('@/views/dashboard/index.vue'), meta: { title: 'Dashboard', icon: 'dashboard', affix: true } } ] }, { path: '/message', component: Layout, meta: { hidden: true }, children: [ { path: '', name: 'Message', component: () => import('@/views/message/index.vue'), meta: { title: '消息中心', icon: 'example', affix: false } } ] }, { path: '/profile', component: Layout, meta: { hidden: true }, children: [ { path: '', name: 'Profile', component: () => import('@/views/profile/index.vue'), meta: { title: '个人中心', icon: 'user', affix: false } } ] }, { path: '/download', component: Layout, meta: { hidden: true }, children: [ { path: '', name: 'Download', component: () => import('@/views/download/index.vue'), meta: { title: '下载中心', icon: 'link', affix: false } } ] } ] /** * 404路由配置 */ export const notFoundRoute: RouteRecordRaw = { path: '/:pathMatch(.*)*', redirect: '/404', meta: { hidden: true } } export const notFoundPage: RouteRecordRaw = { path: '/404', name: 'Page404', component: () => import('@/views/404.vue'), meta: { hidden: true } } /** * 解析组件路径 */ function resolveComponent(componentPath: string) { const loader = findComponentLoader(componentPath) if (loader) { return loader } console.warn( `Component ${componentPath} not found in componentMap or views glob; check DB component 字段与 map 是否一致` ) // 多段路径禁止再用模板字符串动态 import,否则生产环境报错 unknown variable dynamic import return () => import('@/views/404.vue') } /** * 将菜单数据转换为路由格式 */ export const transformMenusToRoutes = (menus: any[]) => { if (!menus || !Array.isArray(menus)) { return [] } const transformRoute = (menu: any, parentName?: string): RouteRecordRaw => { let routeName = menu.name // 检查名称冲突:如果子路由名称与父路由名称相同,Vue Router 4 会报错 if (routeName && parentName && routeName === parentName) { routeName = `${routeName}_Child` console.warn(`Route name conflict detected: ${parentName}. Child name changed to ${routeName}`) } let routePath = menu.path const isExternal = /^(https?:|mailto:|tel:)/.test(routePath || '') // Vue Router 4 要求顶层路由路径必须以 / 开头 if (!parentName && routePath && !routePath.startsWith('/') && !isExternal) { routePath = `/${routePath}` } const route: any = { path: routePath, name: routeName, hidden: !!menu.hidden, alwaysShow: !!menu.alwaysShow, meta: { title: menu.meta?.title || menu.name || '', icon: menu.meta?.icon || '', noCache: !!menu.meta?.noCache, affix: !!menu.meta?.affix, breadcrumb: menu.meta?.breadcrumb !== false, activeMenu: menu.meta?.activeMenu, roles: menu.meta?.roles } } if (menu.redirect) { route.redirect = menu.redirect } if (menu.component) { if (menu.component === 'Layout') { route.component = Layout } else if (typeof menu.component === 'string') { // 正常情况:字符串类型 if (menu.component.startsWith('@/views/')) { const componentPath = menu.component.replace('@/views/', '') route.component = resolveComponent(componentPath) } else if (menu.component.startsWith('@/')) { const componentPath = menu.component.replace('@/', '') route.component = () => import(`@/${componentPath}.vue`) } else { route.component = resolveComponent(menu.component) } } else { // 如果后端传回的 component 是一个带有 __file 等不该出现的打包后的对象 // 通过父子路径拼接去 map 里面找,或者直接截取 path const fallbackPath = parentName ? `${parentName.toLowerCase()}/${menu.path}` : menu.path; console.warn(`Invalid component format for path [${menu.path}]. Falling back to use componentMap key: ${fallbackPath}`); route.component = resolveComponent(fallbackPath); } } else { if (!menu.children || menu.children.length === 0) { const inferredLoader = buildInferredComponentPaths(menu, parentName) .map((path) => findComponentLoader(path)) .find(Boolean) route.component = inferredLoader ?? ParentView } else { route.component = Layout } } if (menu.children && menu.children.length > 0) { route.children = menu.children.map((child: any) => transformRoute(child, routeName)) } return route as RouteRecordRaw } return menus.map(menu => transformRoute(menu)) } const router = createRouter({ history: createWebHistory('/'), routes: constantRoutes, scrollBehavior: () => ({ top: 0 }) }) export default router