Lazy Loading in Vue using Webpack's Code Splitting

Posted on Jul 16, 2017

Checkout the tip Dynamic Imports in Vue.js for better performance in VueDose to learn more about this topic!

We could apply lazy loading and code splitting in 3 different levels in a Vue app:

But there is something they all have in common: they use dynamic import, which is understood by Webpack since version 2.

Lazy load in Vue components

This is well explained in the "Load components when needed with Vue async components" on Egghead.

It's as simple as using the import function when registering a component:

Vue.component("AsyncCmp", () => import("./AsyncCmp"));

And using local registration:

new Vue({
  // ...
  components: {
    AsyncCmp: () => import("./AsyncCmp")
  }
});

By wrapping the import function into an arrow function, Vue will execute it only when it gets requested, loading the module in that moment.

If the component importing is using a named export, you can use object destructuring on the returned Promise. For example, for the UiAlert component from KeenUI:

...
components: {
  UiAlert: () => import('keen-ui').then(({ UiAlert }) => UiAlert)
}
...

Lazy load in Vue router

Vue router has built in support for lazy loading. It's as simple as importing your components with the import function. Say we wanna lazy load a Login component in the /login route:

// Instead of: import Login from './login'
const Login = () => import("./login");

new VueRouter({
  routes: [{ path: "/login", component: Login }]
});

Lazy load a Vuex module

Vuex has a registerModule method that allow us to dynamically create Vuex modules. If we take into account that import function returns a promise with the ES Module as the payload, we could use it to lazy load a module:

const store = new Vuex.Store()

...

// Assume there is a "login" module we wanna load
import('./store/login').then(loginModule => {
  store.registerModule('login', loginModule)
})

Conclusion

Lazy loading is made extremely simple with Vue and Webpack. Using what you've just read you can start splitting up your app in chunks from different sides and load them when needed, lightening the initial load of the app.

Alex Jover

ALEX JOVER

Google Dev Expert, Vue team member, cats and dance lover. Find here all my teachings about web development, web performance and more.

Alex Jover Morales © 2018