vite动态添加路由(打包)
开发环境没有错,在生产上报错** Failed to fetch dynamically imported module: http://xxxxx/@/views/app/xxxxxxx**
1、动态路由添加后,vite 打包后报错
const handleHome = (data)=>{
const routes = []
for(const item of data){
const route = {
const importPromise = import(/* @vite-ignore */ `/@/${item.component}`)
return importPromise.then((module)=>{
const Component = module.default ||module
Component.query = item.query
return Component
})
}
if(item.children && item.children.length > 0){
route.children = handleHome(item.children)
}
routes.push(route)
}
return routes
}
2、defineAsyncComponent组件的方式,vite 打包报错
import { defineAsyncComponent } from 'vue'
const AsyncFooWithOption = (path) =>defineAsyncComponent{
loader:()=>import ('../../${path}'),
delay:2000,
timeout:3000
}
....格式化数据方法省略....
component:AsyncFooWithOption(item.component)
3、第三种写法,找出目录下的所有的.vue文件,与返回的路由地址做匹配,vite 打包后,完美解决
const importRoute = import.meta.glob('../../views/**/*.vue');
component: importRoute[`../../${item.component}`],