Blog>
Snippets

Implement Vue.js 3 route-level code-splitting for SEO

Use Vue.js 3's dynamic import feature to split code at the route level, reducing the initial load time and improving SEO.
import { createRouter, createWebHistory } from 'vue-router';

const routes = [
  {
    path: '/home',
    name: 'Home',
    // Route level code-splitting
    // This generates a separate chunk (home.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "home" */ './views/Home.vue')
  },
  {
    path: '/about',
    name: 'About',
    // Route level code-splitting
    // This generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
  }
  // other routes...
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

export default router;
This code demonstrates how to use Vue Router with Vue.js 3 to enable route-level code-splitting. Each route's component is dynamically imported, meaning it's only fetched when that route is navigated to, improving the initial load time and thus benefiting SEO.