Lazy Loading Vue Router Components
Published:Intro
In this post we will cover lazy loading Vue Components when using the Vue Router. We’ll also touch on how and why lazy loading is used as well as give some examples of how we like to implement it into our code.
What is Vue Router?
Vue Router 4 is a powerful router that is highly recommended for any Vue projects that require routing. It is incredibly feature rich, and today I am going to focus on lazy loading our components. Vue Router installation will not be covered in this post. Head over to the Vue Router docs if you need those instructions.
Why Lazy Loading?
While there is no denying the power one is granted by today’s modern JS frameworks like Vue, this power comes at a price. I think everyone wants to keep their build sizes down and lazy loading can help with that. When we use lazy loading, it splits the route components into chunks. This saves us on build size and page speeds. Now that we have covered a couple benefits of lazy loading, let’s take a look at how we implement it.
Let’s look at some code
We will start off looking at how Vue Router introduces routes and their way of assigning route components. Here is an example of a router.js
.
import BlogPost from './views/BlogPost.vue';
// ...
const router = createRouter({
routes: [
{
path: '/blog/:postId',
component: BlogPost,
},
],
// ...
});
// ...
As per Vue Router docs, we can lazy load a component (serving as a view in this case) with the following code…
// ...
const router = createRouter({
routes: [
{
// blog post page
path: '/blog/:postId',
component: () => import('./views/BlogPost.vue'),
},
],
// ...
});
//...
Notice the difference between the two; the first example imports the component at the start of the file. This happens regardless if the component is ever used. In the second example, we have moved the import statement into a dynamic import (FYI: Vue Router docs recommend dynamic imports be used on all routes.) This means the component is imported only when the route is accessed for the first time. After the first visit to the route, any subsequent visits serve the component from cache.
Let’s get DRY
Since the route’s component
option will accept anything that returns a promise, it can be helpful and can save you time if you write your own function to use here. Here is an example of that…
function lazyLoad(pathToComponent) {
return () => import(pathToComponent);
}
Using our handy function above, our router.js
now looks like this…
function lazyLoad(pathToComponent) {
return () => import(pathToComponent);
}
// ...
const router = createRouter({
routes: [
{
// blog post page
path: '/blog/:postId',
component: lazyLoadComponent('./views/BlogPost.vue'),
},
],
// ...
});
//...
Conclusion
In closing, we covered how and why we use lazy loading components with the Vue Router. We also looked at a couple code examples to help you get started in your project. If you have any feedback, please send us a message!