If you’re working in Vue, the Vue CLI is an amazing thing. There are a lot of moving parts in modern JavaScript development and the CLI makes managing these very easy.

One of the niceties that the CLI will give you is the ability to compile your Vue components into custom HTML tags. I’ve talked about how to get this set up in What are custom HTML elements and in Building custom elements from Vue CLI. This article is about how to then compile and export those components so that they are ready to put on any web page.

Transpiling Vue to Custom Components

The process of turning Vue into an official, browser supported Web Component is handled via a Vue build tool called @vue/web-component-wrapper. This will take your component and build it into the format needed by the Web Component standard. This transpiling from a Vue component to a custom component is already built into Vue CLI, so if your project was created with Vue CLI, all you have to do to export a component to a custom component is this:

vue-cli-service build --target wc --name my-blink 'src/components/Blink.vue'

This will create three files in your dist folder:

FilenamePurpose
my-blink.jsThe code for your component minus the Vue library
demo.htmlA simple demo HTML file for your component
my-blink.js.mapThe debugging information for your browser
my-blink.min.jsThe minified version of the component
my-blink.min.js.mapThe debugging information for the minified version

The important thing to know here is that you must include the Vue library in your HTML wherever you want to use your component. It’s not included in the build itself. If you look at the demo HTML file that was created during the build process, you’ll see that in action.

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

<my-blink></my-blink>

You can then use that demo.html file to test out the component.

What if you have more than one component?

What if you have multiple components that you want to turn into Web Components? You don’t need to build each one individually, you can instead build them all at once.

vue-cli-service build --target wc-async --name demo 'src/components/*.vue'

This will build your components into multiple files that are actually lazy loaded into the browser. If you don’t use a certain component, its file won’t be loaded in. Nice!

But what about the --name? When you defined that in your single component build, it made the tag that name. But here you have multiple components. What does it do now?

Here, --name is used as a prefix for your tags. So if your Vue component is named blink and the --name is defined as demo, then your tag will export as demo-blink.

And that’s it

Now you can build your Vue components, take the js files from dist and drop them onto any web page. Then just include the tag anywhere in your HTML and BOOM Vue components on any page.