在写业务时候碰到需要有一个页面多个子入口,并且使用的框架无法用动态路由匹配来新增子路由,所以采用vue3的APIdefineAsyncComponent来实现动态路由异步加载的方式实现
// 加载函数
loader: () => import('./Foo.vue'),
// 加载异步组件时使用的组件
loadingComponent: LoadingComponent,
// 展示加载组件前的延迟时间,默认为 200ms
delay: 200,
// 加载失败后展示的组件
errorComponent: ErrorComponent,
// 如果提供了一个 timeout 时间限制,并超时了
// 也会显示这里配置的报错组件,默认值是:Infinity
timeout: 3000
})
采用vite开发阶段引入组件采用相对路径的方式() => import('./Foo.vue'),编译无任何问题,打包上线之后报错:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. index.fbbc90de.js:15 TypeError: Failed to fetch dynamically imported module: http://xxxxxx/route/index.vue
- 通过报错分析出路劲为组件路劲地址被打包成根目录下的路径,所以找不到改文件
- 知道是路劲解析问题之后、从文件引入方式出发寻找解决问题方案,锁定vite文档地址
// Vite 支持使用特殊的 `import.meta.glob` 函数从文件系统导入多个模块:
const modules = import.meta.glob('./dir/*.js')
// vite 生成的代码
const modules = {
'./dir/foo.js': () => import('./dir/foo.js'),
'./dir/bar.js': () => import('./dir/bar.js'),
}
const routePages: routePagesType = {
'accountRoute': '../routePage/accountRoute/index.vue',
'BusinessRoute': '../routePage/BusinessRoute/index.vue',
'messageLogRoute': '../routePage/messageLogRoute/index.vue',
'businessRecordRoute': '../routePage/businessRecordRoute/index.vue',
'payWaterRoute': '../routePage/payWaterRoute/index.vue',
'billPrintingRoute': '../routePage/billPrintingRoute/index.vue',
}
const modules = import.meta.glob('../routePage/*/index.vue')
const loaderRoute = (route: routeKey) => {
const loader = modules[route]
return defineAsyncComponent({
loader,
loadingComponent: SuspenseLoading,
delay: 200,
})
}