Tutorial

Lazy Loading Components with vue-cli 3, webpack & Vue Router

Published on May 17, 2018
Default avatar

By Daniel Schmitz

Lazy Loading Components with vue-cli 3, webpack & Vue Router

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

SPAs (Single Page Applications) often consist of dozens or even hundreds of components that can be divided into several JavaScript bundle files. The goal of this post is to show one way to do this division and how to load each file asynchronously, only when the component is requested from a route change. This asynchronous behavior is called lazy loading and allows for a smaller initial bundle size.

Project Creation

Let’s start a new project and use vue-cli 3 to create it according to the following command:

$ vue create my-app
...
Vue CLI v3.0.0-beta.9
? Please pick a preset: Manually select features
? Check the features needed for your project:
 ( ) TypeScript
 ( ) Progressive Web App (PWA) Support
 (*) Router
 ( ) Vuex
 ( ) CSS Pre-processors
>(*) Linter / Formatter
 ( ) Unit Testing
 ( ) E2E Testing

Tip: Choose to group all the config rules in the package.json file.

The project created has two views: Home.vue and About.vue. When we run the project, through the yarn serve or npm run serve command, the views are accessed through the top menu, similar to the following figure:

Newly created project

These two files, Home.vue and About.vue, are loaded when the application initializes. For a non-trivial projects with a lot of components, it’s often not viable to load all the files at once. We need to load the files as they are requested.

We can implement the lazy loading easily, thanks to an upcoming JavaScript feature, dynamic imports, that webpack supports. Currently, the src/router.js file has the following code:

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/about',
      name: 'about',
      component: About
    }
  ]
})

To setup lazy loading, we change the src/router.js file to the following instead:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

function loadView(view) {
  return () => import(/* webpackChunkName: "view-[request]" */ `@/views/${view}.vue`)
}

export default new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: loadView('Home')
    },
    {
      path: '/about',
      name: 'about',
      component: loadView('About')
    }
  ]
})

Here’s a breakdown of what we’ve changed:

1- We have removed the static imports for the home and about components.

2- We have created the loadview function, which uses the import function to dynamically import a Vue component.

3- In the import function, we have used /* webpackChunkName: "view-[request]" */ to mark the name of each file that will be imported dynamically.

4- The route configuration uses the loadView method, passing the name of the component.

This way, when we compile the project through npm run build or yarn build, we get the following result:

Building the app

Notice that two files have been created: view-Home-vue... and view-About-vue.... They will be loaded on demand on the production server:

Lazy loading in action

Dynamic Imports and ESLint

At the time of this writing, there’s a small ESLint due to the fact that it can’t recognize the import function, similar to the following figure:

ESLint error

To fix it, open the package.json file and add the following configuration:


 "eslintConfig": {
    "root": true,
    "parserOptions": {"parser": "babel-eslint"},
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ]
  },

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Daniel Schmitz

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel