Skip to content

WX-DongXing/unplugin-web-components

Repository files navigation

unplugin-web-components

Building vue3 components to webComponents on vite

Install

npm i -D unplugin-web-components

Use

lib/index.ts

import { defineCustomElement } from 'vue'
import { styles } from 'virtual:unplugin-web-components'
import Example from '@/components/Example.vue'

const WCExample = defineCustomElement(Object.assign(WCExample, { styles }))

customElement.define('wc-example', WCExample)

env.d.ts

declare module 'virtual:unplugin-web-components' {
  export const styles: string[]
}

vite.config.ts

import vue from '@vitejs/plugin-vue'
import WebComponents from 'unplugin-web-components/vite'

export default defineConfig({
  define: { 'process.env.NODE_ENV': '"production"' },
  plugins: [vue(), WebComponents()],
  build: {
    lib: {
      name: 'WCExample',
      formats: ['es', 'umd']
      entry: resolve(__dirname, 'lib/index.ts'),
      fileName: (format) => `wc-example.${format}.js`,
    }
  }
})
Vite
// vite.config.ts
import WebComponents from 'unplugin-web-components/vite'

export default defineConfig({
  plugins: [
    WebComponents({
      /* options */
    })
  ]
})

Example: playground/


Rollup
// rollup.config.js
import WebComponents from 'unplugin-web-components/rollup'

export default {
  plugins: [
    WebComponents({
      /* options */
    })
  ]
}


Webpack
// webpack.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-web-components/webpack')({
      /* options */
    })
  ]
}


Nuxt
// nuxt.config.js
export default {
  buildModules: [
    [
      'unplugin-web-components/nuxt',
      {
        /* options */
      }
    ]
  ]
}

This module works for both Nuxt 2 and Nuxt Vite


Vue CLI
// vue.config.js
module.exports = {
  configureWebpack: {
    plugins: [
      require('unplugin-web-components/webpack')({
        /* options */
      })
    ]
  }
}


esbuild
// esbuild.config.js
import { build } from 'esbuild'
import WebComponents from 'unplugin-web-components/esbuild'

build({
  plugins: [WebComponents()]
})


License

MIT

Copyright (c) 2022 Dong Xing