Blog>
Snippets

Lazy Loading Routes in Vue.js 3 SPA

Implementing lazy loading for routes in a Vue.js 3 application to improve initial load time by only loading components when they are needed.
const Home = () => import(/* webpackChunkName: "home" */ './views/Home.vue');
Defines the Home component to be lazy loaded using the dynamic import syntax, which will only load the component when it's required.
const About = () => import(/* webpackChunkName: "about" */ './views/About.vue');
Defines the About component to be lazy loaded in the same manner as the Home component.
import { createRouter, createWebHistory } from 'vue-router';

// Create router instance
const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', name: 'Home', component: Home },
    { path: '/about', name: 'About', component: About }
  ]
});

export default router;
Sets up the Vue Router with a history mode and defines the routes. The components for these routes are the lazy loaded Home and About.