Join egghead, unlock knowledge.

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
Become a member
to unlock all features

Level Up!

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


    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.



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

    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.

    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.

    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.

    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.

    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.

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