I’ve been reading around on articles about creating vue web/lib components. However, I could not find one handling multiple components. There is also a little emphasis on producing different target builds — the Library and Web Components. Thence, here it is — my attempt to share my experience setting up a multiple web and library components using vue.

On this reading, we will cover the following parts:

  • Configuring two target builds: Web and Library builds
  • Handling multiple components
  • Publishing the vue components as a scoped package to npm
  • Bonus — usage of the new published package
  • Bonus — how to work with the new components and see it in action

I know most developers want to get on the gist right away, so let’s start.


Initial Setup

Pre-requisites

Make sure first that vue cli and vue cli-service-global was installed globally. They will be use on building packages and serving components

npm install -g @vue/cli @vue/cli-service-global

Create a vue project

vue create dxc-components

It will prompt you with some setup options, you should just choose “default” and hit enter.


Build Targets

We have to specify our build configurations and to do that, we need to make changes on package.json. In scripts, update that portion to have it like this —

"scripts": {
     "serve": "vue-cli-service serve",
     "build": "npm run build:wc & npm run build:lib",
     "lint": "vue-cli-service lint",
     "build:lib": "vue-cli-service build --target lib --name dxc-components 'src/main.js'",
     "build:wc": "vue-cli-service build --target wc --name dxc-components 'src/components/*.vue'"
   },

build:lib will build our package designed for library use. Example

import MyComponent from 'my-component';  

export default {
   components: {
       MyComponent,   
   },
  // rest of the component 
}

build:wc will allow usage via <script> tag directly in the browser . Example

<script src="https://unpkg.com/vue"></script> <script src="https://unpkg.com/my-component"></script>
... 
<my-component></my-component> 
...

the 'src/components/*.vue' , is the entry that will register multiple components found insrc/components directory. In our configuration,--name was set to dxc-components , with that, the result of the bundle will be registered as <dxc-components-my-component> . That is, if we have a component named MyComponent.vue in src/components .

**Note! **When you only have one component inside src/components the --name will be use as the tag element name. So, the resulting element will be <dxc-components /> instead of <dxc-components-my-component />

The build on script commands will allow us to easily build both lib and web components.

#npm #web-components #vue #components-library

Creating and Publishing Multiple Vue Web and Library Components
24.40 GEEK