[Vuejs]-How to add dynamic/async/lazy components in VueJs

3👍

you can combine async component and dynamic import to achieve this

Vue.component('foo', () => {
    if(currentView === 'a') {
      return import('./A1Component.vue')
    } else {
      return import('./B2Component.vue')
    }
})

to use dynamic import, you’ll need add syntax-dynamic-import plugin to your Webpack

Babel plugin:
https://babeljs.io/docs/plugins/syntax-dynamic-import/

Webpack Plugin:
https://github.com/airbnb/babel-plugin-dynamic-import-webpack

👤cwang

2👍

Install required babel plugin:

npm install --save-dev babel-plugin-syntax-dynamic-import

Create .babelrc in your project root, include bellow short code in file:

{
    "plugins": ["syntax-dynamic-import"]
}

after you can import with this way :

const Foo = () => import('./Foo.vue')

finaly run npm build(vue-cli) or npm run watch(laravel)

0👍

Hey man I was on this same kind of problem googled almost 4-5 hours.

The splitting didn’t work as I expected. With babel preset es2015 it did work just fine on the DEV server, when building the code uglifier errored.
After I got it to build, it worked beautifully.
I don’t think you have to tell webpack to split the code, it’s all automagical when you jsut use the right type of importing, and that is the const Foo = () => import('./Foo.vue') type

All the imports done like that create a split point, and if you don’t want it to split, yo uhave to take that extra step in the docs
Yes, but it’s not per folder, but per FILE basis
so if you have 5 folders with 25 files, it’ll become 25 bundle files, automatically loaded when needed

This would definitely help – https://vuejsdevelopers.com/2017/07/03/vue-js-code-splitting-webpack/

Leave a comment