Home Web Front-end CSS Tutorial Lazy Load Routes in Vue with webpack Dynamic Comments

Lazy Load Routes in Vue with webpack Dynamic Comments

Mar 27, 2025 am 09:47 AM

Lazy Load Routes in Vue with webpack Dynamic Comments

The JavaScript routing mechanism usually specifies which relative URL pattern corresponds to which component rendering. For example, the /about path should be rendered<about></about> Components. This article will explain how to achieve this with lazy loading in Vue/Vue Router and do it as concisely as possible.

A repository of code containing all of this article is available on GitHub.

You may have seen Vue routes (URLs):

 import Vue from 'vue'
import VueRouter from 'vue-router'

import Home from '../views/Home.vue'
import About from '../views/About.vue'
import Login from '../views/Login.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', name: 'Home', component: Home },
  { path: '/about', name: 'About', component: About },
  { path: '/login', name: 'Login', component: Login }
]

const router = new VueRouter({
  routes
})

export default router
Copy after login

This code will load in / path<home></home> Component, loading in /about path<about></about> Component, loading in /login path<login></login> Components.

However, this method of code segmentation is not done well, as all three components are packaged together instead of loading dynamically as needed.

Here is an improvement that uses dynamic import statements and webpack chunk names for code segmentation:

 const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import(/* webpackChunkName: "Home" */ '../views/Home.vue')
  },
  {
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "About" */ '../views/About.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "Login" */ '../views/Login.vue')
  }
]
Copy after login

This approach is good, without obvious drawbacks, just slightly lengthy and repetitive. As a good developer, let's do some abstraction to improve it, use an array and do .map operations:

 const routeOptions = [
  { path: '/', name: 'Home' },
  { path: '/about', name: 'About' },
  { path: '/login', name: 'Login' }
]

const routes = routeOptions.map(route => {
  return {
    ...route,
    component: () => import(`@/views/${route.name}.vue`)
  }
})

const router = new VueRouter({
  routes
})
Copy after login

Now we have reduced the use of component keys and instead use the route name as an argument to the import function.

But what if we want to set the chunk name ?

As far as I can tell, you can't use dynamic annotations in JavaScript without some kind of build step. So in this case we sacrifice comments (webpackChunkName) to reduce the amount of code writing. It all depends on which method you prefer.

Just kidding, let's solve this problem.

Starting from webpack 2.6.0, placeholders [index] and [request] are supported, which means we can set the name of the generated chunk like this:

 // ...

const routeOptions = [
  { path: '/', name: 'Home' },
  { path: '/about', name: 'About' },
  { path: '/login', name: 'Login' }
]

const routes = routeOptions.map(route => {
  return {
    ...route,
    component: () => import(/* webpackChunkName: "[request]" */ `../views/${route.name}.vue`)
  }
})

const router = new VueRouter({
  routes
})
Copy after login

very good! Now we have all the features, as well as dynamic loading routes with named chunks. It works on Vue 2 and Vue 3. You can check it by running npm run build in the terminal:

However, we can also go a step further by grouping lazy load routes into named chunks instead of individual components. For example, we could create some groups that put together the most important components and the rest in another "less important" group. We just need to update webpackChunkName to replace the [request] placeholder we used before:

 const routes = [
  {
    path: "/",
    name: "Home",
    component: () =>
      import(/* webpackChunkName: "VeryImportantThings" */ "../views/Home.vue")
  },
  {
    path: "/about",
    name: "About",
    component: () =>
      import(/* webpackChunkName: "VeryImportantThings" */ "../views/About.vue")
  },
  {
    path: "/login",
    name: "Login",
    component: () =>
      import(/* webpackChunkName: "NotSoImportant" */ "../views/Login.vue")
  },
  {
    path: "/contact",
    name: "Contact",
    component: () =>
      import(/* webpackChunkName: "NotSoImportant" */ "../views/Contact.vue")
  }
];
Copy after login

Now our four components are grouped into two separate chunks.

That's it! A technique for lazy loading routes in Vue, and some suggestions on how to name and group them at build time.

The above is the detailed content of Lazy Load Routes in Vue with webpack Dynamic Comments. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

How to Use CSS Grid for Sticky Headers and Footers How to Use CSS Grid for Sticky Headers and Footers Apr 02, 2025 pm 06:29 PM

CSS Grid is a collection of properties designed to make layout easier than it’s ever been. Like anything, there&#039;s a bit of a learning curve, but Grid is

See all articles