webpack and Vue were born to be together. When using webpack as the bundler for your Vue project, it's possible to make your components load asynchronously or when they are needed. This is commonly known as lazy loading.
Getting ready
The prerequisite for this recipe is Node.js 12+.
The Node.js global objects that are required for this recipe are as follows:
- @vue/cli
- @vue/cli-service-global
To complete this recipe, we will use our Vue project and the Vue CLI, as we did in the Creating a component mixin recipe.
How to do it...
Follow these steps to import your component with a lazy loading technique:
- Open the App.vue file.
- In the <script> part of the component, import the defineAsyncComponent API from Vue and pass the lazyLoad component function as an argument of the defineAsyncComponent function:
<script>
import { defineAsyncComponent } from 'vue';
import StarRating from './components/StarRating.vue';
export default {
name: 'App',
components: {
StarRating,
MaterialButton: defineAsyncComponent(() => import('./components/MaterialButton.vue')),
MaterialCardBox: defineAsyncComponent(() => import('./components/MaterialCardBox.vue')),
},
methods: {
resetVote() {
this.$refs.starRating.vote(0);
this.$refs.starRating.voted = false;
},
forceVote() {
this.$refs.starRating.vote(5);
},
},
};
</script>
<style>
body {
font-size: 14px;
}
</style>
How it works...
Vue now uses a new API called defineAsyncComponent to identify a component as an asynchronous component and receives as an argument, another function that returns the import() method.
When we declare a function that returns an import() function for each component, webpack knows that this import function will be code-splitting, and it will make the component a new file on the bundle.
See also
- You can find more information about async components at https://v3.vuejs.org/guide/component-dynamic-async.html#dynamic-async-components.
- You can find more information about the TC39 dynamic import at https://github.com/tc39/proposal-dynamic-import.