Route-Level Code Splitting in Vue Router

If you've created a project with Vue CLI recently, you might have been shocked to discover this in your router.js:

export default new Router({
  routes: [
    {
      path: "/",
      name: "home",
      component: Home
    },
    {
      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")
    }
  ]
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

For Small Vue Projects

Old-style routing should be fine:

{
  path: '/',
  name: 'home',
  component: Home
},
1
2
3
4
5

For Large Vue Projects

Here the About page gets loaded only when the user visits it:

{
  path: '/about',
  name: 'about',
  component: () => import('./views/About.vue')
}
1
2
3
4
5

This is great for sites with a lot of pages.

For Greater Chunking Control

Suppose your site has a Help section that consists of About and FAQ pages. You could put them into a single "help" chunk by specifying /* webpackChunkName: "help" */:

{
  path: '/about',
  name: 'about',
  component: () => import(/* webpackChunkName: "help" */ './views/About.vue')
},
{
  path: '/faq',
  name: 'faq',
  component: () => import(/* webpackChunkName: "help" */ './views/FAQ.vue')
}
1
2
3
4
5
6
7
8
9
10

Official Docs

The official documentation on route-level code splitting: Lazy Loading Routes


Copyright © 2018 Daniel and Audrey Roy Greenfeld.
Site Map

Last Updated: 8/28/2018, 3:59:47 PM