Vue.js lazy load custom library component

1.3k Views Asked by At

I've created a small library with 2 components and compile it in UMD. I export components like that :

import Btn from './components/Btn'
import Other from './components/Other'

export { Btn, Other }

I've tried to use lazy import or export as default... not better. In my app, i import library as npm dependency. After, in app.vue, I would like to load a component (like Btn) with lazy loading

export default {
  name: 'App',
  components: {
    Btn: () => import('myLib').then(m => m.Btn)
  }
}

That's work but it's not good for me because all library is load and after I use Btn. There is a way to load directly component with true lazy load ?

Another way is to full lazy load library a the first use...

1

There are 1 best solutions below

7
On

Try this (untested). Instead of immediately importing modules in your library, export functions. Remove all import statements from the library:

<library>.js

export default {
  Btn: () => import('./components/Btn'),
  Other: () => import('./components/Other')
}

Use it like:

import myLib from './myLib'
export default {
  name: 'App',
  components: {
    Btn: myLib.Btn
  }
}

You can do it without a library too:

export default {
  name: 'App',
  components: {
    Btn: () => import('./components/Btn')
  }
}