Lazy Loading Routes in Vue Router
Lazy Loading Routes refer to a way of developing web applications in which it is possible to optimize performance improvement concerning loading. Instead of loading a whole application at once, lazy loading will allow parts of the app, such as specific routes or components, to load only when needed. This reduces the initial load time and hence improves performance, especially for large applications.
How Lazy Loading Works in Vue?
In a common application, routes and components load together; thus, the initial load is heavy and slow. In the case of lazy loading, every route or component is loaded only when the user navigates to this route.
For example, imagine your application has lots of pages, here understood as a route. Each of the pages can be lazy-loaded; meaning, it will just run what's necessary code in the current page. You then navigate to another route and automatically load up that particular page's code.
Steps to implement Lazy Load Routes
Step 1: Set Up Your Vue Project
If you don’t have an already created Vue.js project, you can create na w project using Vue CLI. This command can also be used to create a vite project.
npm create vue@latest

Step 2: Navigate to the project's root directory:
cd lazyloadingexample
Step 3: To install all packages, run this command:
npm install
Step 4: If Vue Router is not already installed, install it in your project:
npm install vue-router
Step 5: Run this command to execute the Project:
npm run dev
Project Structure:

Updated Dependencies:
"dependencies": {
"pinia": "^2.1.7",
"vue": "^3.4.29",
"vue-router": "^4.4.5"
}
Implementation of Lazy loading in Webpack and Vite are different. Let’s see how to set up lazy loading using both metods:
Using Webpack
Webpack in Vue.js refers to the tool that bundles all your project files, including JavaScript and CSS files, images, and so on, into fewer files, which the browser will load. It helps manage files enormously, reduces loads time, and encourages features like Vue components, code splitting, and hot module replacement (auto-refresh during coding). It helps build fast and efficient applications with Vue.js, particularly in production.
Syntax:
const Components_name= () => import(/* webpackChunkName: "Chunk_name" */ '../views/Components_name.vue');
Example: This example demonstrates lazy loading using Webpack.
//src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'Home',
component: () => import(/* webpackChunkName: "main" */ '../views/HomeView.vue')
},
{
path: '/about',
name: 'About',
component: () => import(/* webpackChunkName: "main" */ '../views/AboutView.vue')
}
]
})
export default router
//src/App.vue
<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
</script>
<template>
<header>
<div class="wrapper">
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
</nav>
</div>
</header>
<RouterView />
</template>
//src/main.ts
import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')
Output:
Using vite
Vite in Vue.js is a fast build tool which creates and bundles your app files for development and production. It is faster than Webpack as it only processes the files you are actually working on. It supports Vue components, hot module replacement (hot updates while coding), and gives faster loading times with easier configuration, making it really easy to develop and optimize Vue apps.
Syntax:
const ComponentName = () => import('path/to/your/component');
Example: This Example is used to demonstrate the configuration of lazy loading with Vite.
// src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'Home',
component: () => import('../views/HomeView.vue')
// Lazy load HomeView.vue
},
{
path: '/about',
name: 'About',
component: () => import('../views/AboutView.vue')
// Lazy load AboutView.vue
}
]
})
export default router
//vite.config.ts
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
vueJsx(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
build: {
rollupOptions: {
output: {
// Group components into the same chunk
manualChunks(id) {
'main';['../views/HomeView.vue', '../views/AboutView.vue']
}
}
}
}
}
)
// src/App.vue
<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
</script>
<template>
<header>
<div class="wrapper">
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
</nav>
</div>
</header>
<RouterView />
</template>
// src/main.ts
import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.mount('#app')
Output: