When building apps with a bundler, the JavaScript bundle can become quite large, and thus affect the page load time. It would be more efficient if we can split each route's components into a separate chunk, and only load them when the route is visited.
Combining Vue's async component feature and webpack's code splitting feature, it's trivially easy to lazy-load route components.
First, an async component can be defined as a factory function that returns a Promise (which should resolve to the component itself):
const Foo = () => Promise.resolve({ /* component definition */ })
Second, in webpack 2, we can use the dynamic import syntax to indicate a code-split point:
import('./Foo.vue') // returns a Promise
Note: if you are using Babel, you will need to add the syntax-dynamic-import plugin so that Babel can properly parse the syntax.
Combining the two, this is how to define an async component that will be automatically code-split by webpack:
const Foo = () => import('./Foo.vue')
Nothing needs to change in the route config, just use Foo
as usual:
const router = new VueRouter({
routes: [
{ path: '/foo', component: Foo }
]
})
Sometimes we may want to group all the components nested under the same route into the same async chunk. To achieve that we need to use named chunks by providing a chunk name using a special comment syntax (requires webpack > 2.4):
const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue')
const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue')
const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue')
webpack will group any async module with the same chunk name into the same async chunk.