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

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"    ]  },
SUSCRÍBETE A NUESTRO BOLETÍN 
No te pierdas de nuestro contenido ni de ninguna de nuestras guías para que puedas avanzar en los juegos que más te gustan.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top