别着急,坐和放宽
Vue使用动态路由导入文件,打包之后出现报错:
通过这种方式导入的组件在打包时不会被Vite导入。
如图,打包时只添加了定义router时就引入的文件。
使用import.meta,glob
显式导入。
const viewModules = import.meta.glob('../views/**/*.vue')
function dynamicImport(dynamicViewsModules: Record<string, () => Promise<unknown>>, component: string) {
const keys = Object.keys(dynamicViewsModules)
const matchKeys = keys.filter((key) => {
return key === component
})
const matchKey = matchKeys[0]
return dynamicViewsModules[matchKey]
}
function transformRoutes(backendRoutes: menuType[]): RouteRecordRaw[] {
return backendRoutes.map(route => {
const item = {
...route,
children: route.children ? transformRoutes(route.children) : []
}
if (route.component) {
item.component = dynamicImport(viewModules, route.component) as any
}
return item as any
})
}