'Vite-Vue3 can not use web component (full build, runtime compiler)

1、Switch to full vue build in vite.config.js:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
        'vue': 'vue/dist/vue.esm-bundler.js'
    }
  }
})

2、Add isCustomElement in main.js:

import { createApp } from 'vue'
import App from './App.vue'

var app = createApp(App);
app.config.isCustomElement = tag => tag === "my-component";

app.mount('#app')

3、Define a web componnet then use it in App.vue:

<template>
    My custom component can NOT display:
    <my-component />
</template>

<script>
class MyComponent extends HTMLElement {
    constructor() {
        super();

        var container = document.createElement('div');
        container.classList.add('container');

        var name = document.createElement('p');
        name.classList.add('name');
        name.innerText = 'Custom component';

        container.append(name);
        this.append(container);
    }
}
window.customElements.define('my-component', MyComponent);
</script>

Result: [Vue warn]: Failed to resolve component: my-component



Solution 1:[1]

The problem is that the skipping component resolution should be defined on the vite.config.js file instead of the main.js

Remove the line app.config.isCustomElement = tag => tag === "my-component"; from the main.js

Update the vite.config.js with the configuration to skip the component resolution

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue({
      template: {
        compilerOptions: {
          isCustomElement: (tag) => tag === "my-component"
        }
      }
    })],
  resolve: {
    alias: {
        'vue': 'vue/dist/vue.esm-bundler.js'
    }
  }
})

Reference: Vue and Web Components

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David SK