TIL: Lazy Loading Vue Router Routes With Dynamic Imports
A single-page app that loads every route’s components upfront gets slow fast. Vue Router’s lazy loading splits the bundle per route.
const router = new VueRouter({
routes: [
{
path: '/dashboard',
component: () => import('./views/Dashboard.vue')
},
{
path: '/settings',
component: () => import('./views/Settings.vue')
}
]
})
The arrow function with dynamic import tells webpack to create a separate chunk for each route. The browser downloads Dashboard.vue only when the user navigates to /dashboard.
With Vue 2 and webpack, this was the standard approach for keeping initial bundle sizes down. I used it on every Vue demo I built at Vonage.
Does this work with Vue CLI?
Yes. Vue CLI uses webpack under the hood. Dynamic imports are detected automatically and split into separate files during build.
What about Vue 3?
Vue 3 uses the same dynamic import syntax. The router API changed slightly but the lazy loading pattern is identical.