Search code examples
typescriptvue.jsvuejs2web-componenttypescript-typings

How can I use webcomponents in a Vue application using Typescript


I am trying to use a web component in my Vue project. However, it is not properly loading. I can see the element in my DOM, but just as an empty tag, not the button it should be. First error I got was the there was no module declared, so I declared one based on suggestion of the error message in tsconst.d.ts:

declare module 'wc-button';

Now, I get a warning in the console from Vue that it is an unknown custom element and if I forget to register it under components. But, since it is a webcomponent, I don't believe that it should be. I can make the message go away by adding the web component to vue.config.ignoredElements, but that is just hiding the message. If I switch my code to javascript, it works fine. So I expect I need to properly declare a module for it, but I am unsure how to proceed. Does anyone have examples or a repo which I could compare to?

My component:

<template>
  <div>
    <button class="btn btn-primary" @click="onClick()">
      Click!
    </button>
    <wc-button type="primary" @click="onClick()">
      Click
    </wc-button>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import wcButton from 'wc-button';

export default Vue.extend({
    data: () => ({
        buttonOutput: 'I was clicked!',
    }),
    methods: {
        onClick(): string {
            return this.buttonOutput;
        },
    },
});
</script>

Solution

  • Found a workaround by importing the web component in my app.js from where Vue app is started. It is a bit hacky, but this allows me to avoid all the typescript issues that were blocking me.