Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

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

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Lazy Load a Route by using the Dynamic Import in Vue.js

    Alex Jover MoralesAlex Jover Morales

    By default, vue-router doesn’t lazy load the routes unless you tell it to do it. Lazy loading of the non-critical routes is one of the points of the PRPL pattern.

    This lesson will show you how you can use the dynamic import to lazy load non-critical routes.

    vueVue.js
    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:01 Right now, we have a build.js file with all the code of the app. By using code splitting, we can separate the routes' code in different bundles. First, let's open the main js file, which is where we have the routes' logic. In order to code a split, unless you load the routes, the only thing we have to use is use the dynamic import instead of the components here.

    00:28 We'll write our function that returns an import. Here, we have to copy the path from the component. In that way, instead of directly loading the component, we are telling the router to use this function, which returns a promise from the import. When it loads, it will load the route.

    00:51 That happens because Vue router has full support for dynamic imports as factory functions. We could do the same thing here for the details component. Don't forget to comment this out.

    01:11 If we save this, we're going to see that it crashes because doesn't recognize the syntax. That's because, if you are using Babel and you don't have the plug-in by default, you have to install --save-dev babel-plugin-syntax-dynamic-import.

    01:37 Then I'm going to open my babelrc file and add the plugin scheme and syntax-dynamic-import. Let's save this and run npm run dev again.

    01:55 Let's reload. If we inaudible work tab right now, apart from the build.js file, we see this one .buildjs file. That's the route for the images component.

    02:15 Let's clean this. If we go to the other route of the editor view, it will load the c..build.js file. Right now, it's loading the code of each route in runtime, reducing the mission load time.

    Discuss

    Discuss