Grouping lazy loaded routes in Vite
If you use vite long enough, you quickly realize that vue-router shows how to group lazy routes into chunks for webpack only. Googling this problem might lead you to this Github issue which vaguely explains how to do it. Evan You, creator of vue.js, decided that only link to the latest glob import feature is enough, but it took me a bit of time to understand, how to apply this feature to vue-router. so to save you some time here is how to do it.
Glob Import
From the page linked in the issue, we can see that vite is able to group imports using the following syntax
const modules = import.meta.glob('./dir/*.js')
which returns an object with path to file as key and function that imports component as a value.
// code produced by vite
const modules = {
'./dir/foo.js': () => import('./dir/foo.js'),
'./dir/bar.js': () => import('./dir/bar.js')
}
This will make sure that chunks are imported in parallel (basically the same as grouping in webpack). So, using this, we can group import routes like this (using glob matching supported by fast-glob
)
const auth = import.meta.glob('/src/views/auth/**/{Login,Signup}.vue');
which will produce something like this depending on your project folder structure.
// code produced by vite
const auth = {
'/src/views/auth/login/Login.vue': () => import('/src/views/auth/login/Login.vue'),
'/src/views/auth/signup/Signup.vue': () => import('/src/views/auth/login/Login.vue'),
}
To assign component to route we can do:
const routes = [
{
path: '/login',
component: auth['/src/views/auth/login/Login.vue'],
},
{
path: '/signup',
component: auth['/src/views/auth/signup/Signup.vue'],
}
]