Klark
Klark

Reputation: 483

Lazy Loading Vue Components with Webpack 2

I am looking to try lazy loading with webpack. I split my app by routes, and every route has required component:

const Home = resolve => {  
    require.ensure([ "../components/Home/Home.vue" ], () => {
        resolve(require("../components/Home/Home.vue"));
    });
};

I got my chunks in separate folders every time I go to different route: bundle1.js, bundle2.js, bundle3.js an on for every component in routes.

Now I don't know how can I load only bundle I need for that route? If I put bundle.js in index.html it will load the whole bundle, but I just want to load the only bundle that I need for that route?

  <body>
    <div id="app"></div>
    <!-- how to auto inject build files here?? -->
  </body>

There is section for Lazy Loading for Vue components. I did that and I get chunks of bundle files. But I don't know what is proper way to include them and load it.

Any help is appreciate. Thanks

Upvotes: 2

Views: 7590

Answers (2)

romandrahan
romandrahan

Reputation: 109

You can find a documentation about how to implement that here:

  1. https://router.vuejs.org/en/advanced/lazy-loading.html
  2. https://v2.vuejs.org/v2/guide/components.html#Async-Components

Upvotes: 3

Roland
Roland

Reputation: 27729

We can implement the lazy loading easily, thanks to an upcoming JavaScript feature, dynamic imports, that webpack supports.

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

function loadView(view) {
  return () => import(/* webpackChunkName: "view-[request]" */ `@/views/${view}.vue`)
}

export default new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: loadView('Home')
    },
    {
      path: '/about',
      name: 'about',
      component: loadView('About')
    }
  ]
})

Of course this answer was taken from this article and i suggest you to read it.

Upvotes: 0

Related Questions