Code split a modal component in VueJS

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 10 months ago

In this lesson I show how to use webpack to code split a modal component in VueJS. Code splitting is a useful tool to help eliminate unused code and only load what's necessary.

Additional Resources

Instructor: [00:00] For this lesson, we're going to look at loading a Vue component dynamically, using Webpack and a click handler. I already have some route splitting going, so if I was to look at my DevTools here, and refresh, you can see that I have a home chunk. When I click about, I get a about chunk.

[00:17] If we scroll down the home page here, you'll notice I've added a modal example...Has a show modal button. When you click this button, it essentially loads a component inside of a modal. I'm using vue-js-modal for this example.

[00:30] This is great for smaller applications. However, if you have an application that has lots of different types of modals, you have to consider splitting and dynamically loading them, so the user doesn't have to download something they may never see.

[00:41] We can do this using dynamic imports, which Webpack gives us for free, just like we use for our routes. Let's head on over to the Hello World Vue component, so you can see how I'm implementing the modal.

[00:51] If I scroll down here, you can see that I'm importing my modal into the script tag. I have a click handler to call the show that implements the show method and shows my modal. In order to dynamically import my modal, I'll just adjust my regular import here to be a function that returns the import instead.

[01:10] Let's look back in Chrome to see if our crude splitting works. If I open up Chrome DevTools, I refresh, and I hit the network tab, click the modal. There it is. My modal is now co-split and loaded when I click the button.

[01:24] What's cool about this is that it's not limited to just dynamically importing modals. You can do all kinds of things. You can machine-load them based on user actions such as scroll in, view port size, click, etc.