How can I build multiple Vue.js components to Native Web Components using Vue CLI at once?

Viewed 1628

I'm new to Vue.js and want to make an SDK of Web Components using it. I can make one single web component like this:

main.js:

import Vue from 'vue';
import App from './App.vue';
import wrap from '@vue/web-component-wrapper';

const customElement = wrap(Vue, App);

window.customElements.define('sky-chat', customElement);

Cli command:

vue build --target wc --name sky-chat ./src/main.js

But this is just for one single component. How can I build a bunch of .vue files to separate web components in separate js files at once?

How can I generate a test html automatically containing all components inside it for testing in dist folder after building?

Thanks

2 Answers

Version 4.3.0 added support for specifying multiple web components to be built via comma-separated glob patterns.

Examples:

vue-cli-service build --target wc --name myprefix src/components/core*.vue,src/components/basic*.vue

vue-cli-service build --target wc --name myprefix src/components/myFirst.vue,src/components/mySecond.vue

This produces an individual web component for each entry point specified, and a single demo.html that contains all components. However, there doesn't seem to be support for separate .js files per web component. The web components are bundled into a single file.

You can create a vue plugin to bundle vue files together.

// plugin.js

// your components
import Component1 from '/src/components/Component1.vue'
import Component2 from '/src/components/Component2.vue'
import Component3 from '/src/components/Component3.vue'

// This exports the plugin object.
export default {
  install (Vue, options) {
     // Add a component or directive to your plugin, so it will be installed globally to your project.
     Vue.component('component1', Component1)
     Vue.component('component2', Component2)
     Vue.component('component3', Component3)
  }
}


// your main vue file:

import myPlugin from './plugin.js'
Vue.use(myPlugin);

new Vue({
//...
})

Now you can use all the components you included in the plugin wherever you want without having to import them in each file.

Did I understand your question correctly?

Related