Version 3: dynamic imports + <component /> (and code splitting for free!)

Let’s see how dynamic imports and <component /> can play together:

With the above solution, import turns into a function which returns a Promise. It will load the desired module at runtime if the Promise resolves (that is, nothing breaks and gets rejected).

So, what is happening here? We still use our new friend <component/> , but this time we are not providing a simple string but a whole component object. What?

As stated in the documentation, the :is prop can contain either:

The name of a registered component, or

A component’s options object

Bang! A “component’s options object”. This is exactly what we need!

Notice how we avoided importing and registering the components because our dynamic import is doing so at runtime ❤ .

There’s more information about Vue and Dynamic Imports in the official documentation.

A little gotcha

Notice that we access our prop this.isCompany outside of the dynamic import statement.

This is mandatory because otherwise Vue cannot do its reactivity magic and update our computed value when the prop changes. Try it out, you’ll see what I mean.

By accessing to our prop outside the dynamic import (by creating a simple name variable) Vue knows that our componentInstance computed property “depends on” this.isCompany , so it will effectively trigger a reevaluation when our prop changes.

A word of caution (updated, August 4th)

When using dynamic imports, Webpack will create (on build time) a chunk file for every file matching the expression inside the import function.

The example above is a little contrived, but imagine that my /components folder contains 800 components. Then Webpack would create 800 chunks.