Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Code split a modal component in VueJS

    Andrew Del PreteAndrew Del Prete

    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 https://vuejs.org/v2/guide/components-dynamic-async.html https://medium.com/js-dojo/3-code-splitting-patterns-for-vuejs-and-webpack-b8fff1ea0ba4



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.