Search code examples
vue.jsvuejs2webpack-2async-components

How to render async-component in vuejs2 with webpack2


I want to render a particular component dynamically so define it as async component like this:

Vue.component('AsyncComponent', function (resolve) {
  require(['./components/async-component.vue'], resolve)
});

But getting this error

Error: Loading chunk 0 failed. at HTMLScriptElement.onScriptComplete (app.js:99)

So the major problem is that the chunk file's path is not specified any where, the throw 404 error, is there any webpack configuration also, that I need to specify.Thank you in advance.


Solution

  • You can just use a dynamic import:

    const AsyncComponent = () => import ('./components/async-component.vue');
    

    Then to register it globally:

    Vue.component('AsyncComponent', AsyncComponent);
    

    or simply:

    Vue.component('AsyncComponent', () => import('./components/async-component.vue');
    

    Although this will not work if you are using vue-loader 13 or above unless you set the esModule option to false. see Release Notes