在vue3+vite2构建项目中使用import动态引入时会报如下示例和警告:
/**
* 转化路由component实例化本地文件
* @param routes asyncRoutes
*/
export function filterAsyncRoutes(routes) {
const res = []
routes.forEach(route => {
let tmp = { ...route }
if (tmp.children) {
tmp.children = filterAsyncRoutes(tmp.children)
}
//在以往的vue2+webpack版本中可以这样导入
tmp.component = () => import(`${route.component}`);
res.push(tmp)
})
return res
}
解决方案
vite2文档中是有说明得仔细查看就会明白,如图:
我们只需按照文档中所介绍得,我们首先在文件中进行声明,然后在需要动态导入的时候去取对应项,如下代码示例:
const modules = import.meta.glob('../views/*/*.vue')
/**
* 转化路由component实例化动态导入本地文件
* @param routes asyncRoutes
*/
export function filterAsyncRoutes(routes) {
const res = []
routes.forEach(route => {
let tmp = { ...route }
if (tmp.children) {
tmp.children = filterAsyncRoutes(tmp.children)
}
tmp.component = modules[`../views/${route.component}`];
res.push(tmp)
})
return res
}