Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    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

    vueVue.js
    webpackwebpack
    javascriptJavaScript
    Code

    Code

    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
    Transcript

    Transcript

    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.

    Discuss

    Discuss