实现自动化路由时,在外层使用await导致build时报错,ERROR: Top-level await is not available in the configured target environment ("chrome87", "edge88", "es2020", "firefox78", "safari13" + 2 overrides)
原来的代码:
const routes = []
const files = await import.meta.glob('./**/*.vue')
for(let key in files) {
await await files[key]().then((res) => {
const fileName = key.match(/\/([\w-]+)\.vue/)[1]
routes.push({
path: '/' + fileName,
component: files[key].default
})
})
}
const router = {
path: '/',
children: routes
}
export default router
然后就想着通过动态的添加路由来实现,即addRoute。
改进后的代码如下:
import router from '@/router
const createDynamicRoute = async (router) => {
const routes = []
const files = await import.meta.glob('./**/*.vue')
for(let key in files) {
await await files[key]().then((res) => {
const fileName = key.match(/\/([\w-]+)\.vue/)[1]
routes.push({
path: '/' + fileName,
component: files[key].default
})
})
}
router.add({
path: '/',
children: routes
})
}
export default createDynamicRoute
修改好后,通过点击导航跳转页面正常,当刷新页面时,控制台报错[Vue Router warn]: No match found for location with path xxxx
原因分析: 动态路由的添加是异步操作,在异步操作还没有完成的时候,页面就加载完了,所以找不到动态路由的路径
最终解决方案:
安装 vite-plugin-top-level-await插件,解决外层使用await