Vue lazy loading with dynamic import

Learn how Vue lazy loading work and how we can split build code dist into chunk so we will not have to load large file all at once. Instead, we will use dynamic import to achieve code splitting. This will chunk your build code into pieces so this way we will improve the SPA web performance at first runtime. How this work is Vue will lazy load the necessary components that use to render to the page, only when users go to a new page that will start to request new components files that are necessary.

Usual import

Route file

import Vue from 'vue';
import VueRouter from 'vue-router';
import FirstPage from '@/pages/FirstPage';

Vue.use(VueRouter);

const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'FirstPage',
      component: FirstPage,
    },
  ],
});

export default router;

First-page component

<template>
  <div>
    <second-page></second-page>
  </div>
</template>

<script>
import SecondPage from '@/pages/SecondPage';

export default {
  components: {
    SecondPage
  }
};
</script>

Dist build

Dynamic import

Route file

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

Vue.use(VueRouter);

const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'FirstPage',
      component: () => import('@/pages/FirstPage'),
    },
  ],
});

export default router;

First-page component

<template>
  <div>
    <second-page></second-page>
  </div>
</template>

<script>
export default {
  components: {
    SecondPage: () => import('@/pages/SecondPage')
  }
};
</script>

Dist build

Conclusion

We can see that the dynamic import will separate the build file on each import or each page/component that we import. So if our page used two-component which render based on the condition the first component condition will be loaded without loading the second component. As VueJs guides, “In general, it's a good idea to always use dynamic imports for all your routes.”