最近通过博客学习了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')
}
当用其来进行路由引入的时候,由于需要在文件中进行判断是否注册为路由组件,所以在通过.then获得相应模块
//组件中
export default defineComponent({
name: 'home',
isRouter: true,//注册为路由
setup() {
}
})
//方法中
const modules = import.meta.glob('../views/**/*.vue')
for (const path in modules) {
modules[path]().then((mod) => {
const file = mod.default;
if (!file.isRouter) return //判断
router.addRoute({
path: `/${file.name}`,
name: `${file.name}`,
component: file //then方法访问到的模块
})
})
}
当通过遍历 modules 对象的 key并且.then后访问到了模块,后再用获取到的模块直接注册路由,这样会不会丧失路由的懒加载效果?
我一直在纠结如果不使用.then的话直接component:modules[key],就可以保留原始的路由懒加载格式,即component:()=>import('路径'),但使用.then后就直接变为了component:组件模块`(>﹏<)′