Vite Plugin Vue Hoist CE Styles

raw JSON →
0.1.3 verified Mon Apr 27 auth: no javascript

A Vite plugin that works around a Vue 3 bug where styles are not properly hoisted for custom elements (CE). It injects CSS into the main bundle entry file instead of relying on scoped styles. Version 0.1.3 is the latest and only release. The plugin is experimental, lacks unit tests, and has specific caveats: CSS imports outside SFCs break the build, and it only works with a limited set of configurations. It differs from alternative solutions by being a targeted patch for a specific Vue 3 issue with custom elements.

error Build fails with 'Cannot read properties of undefined (reading 'css')'
cause Plugin expects an output bundle with a name matching 'index' regex; custom entry names cause undefined reference.
fix
Set indexRe option to match your entry file name, e.g., { indexRe: /my-entry.js/ }.
error ERROR: [vite:css] PostCSS plugin returned something that is not a CSS file
cause Importing a .css file outside SFCs (e.g., in main.ts) triggers PostCSS error because plugin cannot handle it.
fix
Remove global CSS imports; only use SFC styles or CSS modules.
gotcha CSS imports outside of SFCs (e.g., import 'styles.css' in main.ts) break the build.
fix Avoid using global CSS imports; rely on SFC <style> or CSS modules.
gotcha Plugin only replaces styles in bundles named with 'index' (e.g., index.xxx.js). Custom bundle names may not work.
fix Use the indexRe option to match your entry file, or rename entry to 'index'.
gotcha Plugin has no unit tests and is largely untested; use with caution in production.
fix Test thoroughly before deploying. Consider alternative solutions for custom element styles.
npm install vite-plugin-vue-hoist-ce-styles
yarn add vite-plugin-vue-hoist-ce-styles
pnpm add vite-plugin-vue-hoist-ce-styles

Shows how to configure the plugin with Vue's custom element mode and specify the host component.

// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { hoistCeStyles } from 'vite-plugin-vue-hoist-ce-styles'

export default defineConfig({
  plugins: [
    vue({ customElement: true }),
    hoistCeStyles({ hostComponent: 'App.vue' })
  ]
})