如何将 Vue 组件打包为 Web Component 供其他框架使用?
解读
面试官抛出这道题,核心想验证三件事:
- 你是否真的把 Vue 当成“渐进式”框架来用,而不仅局限在 SPA 里;
- 你对 Vue 3 的
@vue/web-component-wrapper与defineCustomElement两条技术路线是否分得清、选得准; - 你是否知道国内真实交付场景里的坑:IE 淘汰但鸿蒙快应用、企微微应用、低代码平台仍要求 Web Component 无依赖、体积敏感、样式隔离严格。
答得太浅(“用 Vue CLI 勾一下 Web Component 选项”)会被追问细节;答得太偏(“自己写 rollup 插件改 runtime”)会被质疑成本。要把“官方能力 + 国内基建 + 性能优化”讲全,才能拿到高分。
知识点
- Vue 3 官方暴露的
defineCustomElement:把单文件组件转成继承自HTMLElement的类,运行时仅依赖@vue/runtime-dom,打包后体积 ~22 KB(gzip)。 - 构建工具链:Vite 原生输出 lib 模式 +
rollupOptions.external = 'vue'即可得到my-element.es.js;若用 Vue CLI 需装@vue/cli-plugin-web-component并开shadow: false避免国内部分容器对 Shadow DOM 的 CSP 限制。 - 样式隔离策略:Shadow DOM 最干净,但穿透企微、飞书 JS-SDK 的弹层时会丢 z-index 层级;国内常见做法是在组件根节点加
data-v-ce-${hash}属性,配合:host()伪类做“半隔离”。 - Props 与事件:Vue 的 props 在 Web Component 上映射为字符串属性,需显式声明
{ type: String, reflect: true };自定义事件用this.$emit('change', detail)自动变成CustomEvent,但低代码平台只认小写、无-事件名,要在emits: ['change']里同时导出ceEventNameMap。 - 跨框架调用:React 17 以下不认 Web Component 的 v-model,需要包一层
reactify-wc;Angular 若开ViewEncapsulation.ShadowDom需把CUSTOM_ELEMENTS_SCHEMA加到 NgModule。 - 体积与复用:若一条业务线要输出 20+ 微件,把 Vue 运行时打进去会重复 20 次;国内大厂标准方案是“external Vue + 公司 CDN 统一复用”,在 CI 里把 Vue 打到
https://static.xxx.com/lib/vue/3.4.21/runtime-dom.esm-browser.prod.js,组件 bundle 只保留业务代码,gzip 后 < 10 KB。 - 兼容性兜底:鸿蒙 3.0 内置浏览器 Chromium 92,支持 Custom Elements V1;但部分政务内网仍用 360 极速内核 86,需要加
@webcomponents/custom-elements垫片,并在入口判断typeof customElements === 'undefined'做动态 polyfill。
答案
分五步落地,每一步都给出国内可复制的命令或代码:
-
初始化工程
npm create vite@latest wc-project --template vue cd wc-project npm i -D @vitejs/plugin-vue @rollup/plugin-node-resolve -
改造组件
新建src/MyButton.ce.vue,后缀.ce.vue告诉 Vite 这是 Custom Element 单文件,内部写法与普通组件一致,但 props 必须写完整类型与 reflect:<template> <button :class="size" @click="handleClick"> <slot/> </button> </template> <script setup> defineProps({ size: { type: String, default: 'medium', reflect: true } }) const emit = defineEmits(['change']) function handleClick(e) { emit('change', { value: e.target.innerText }) } </script> <style scoped> :host { display: inline-block; } button.large { padding: 12px 24px; } </style> -
定义并打包
新建src/my-button.js:import { defineCustomElement } from 'vue' import MyButton from './MyButton.ce.vue' const MyButtonWC = defineCustomElement(MyButton) // 支持按需注册,也支持批量注册 export { MyButtonWC } export default MyButtonWC // 若直接 script 引入,自动注册 if (typeof window !== 'undefined' && window.customElements) { window.customElements.define('my-button', MyButtonWC) }修改
vite.config.js:import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue({ customElement: true })], build: { lib: { entry: 'src/my-button.js', name: 'MyButton', fileName: 'my-button' }, rollupOptions: { external: ['vue'], output: { globals: { vue: 'Vue' } } } } })运行
npm run build得到dist/my-button.es.js(仅业务代码)与dist/style.css(提取后的样式)。 -
发布与复用
把产物推到公司私有 NPM:@xxx/my-button,并在 CDN 补一条映射:{ "my-button": "https://static.xxx.com/lib/my-button/1.0.0/index.es.js" }其他框架直接 script 引入即可:
<script type="module"> import 'https://static.xxx.com/lib/vue/3.4.21/runtime-dom.esm-browser.prod.js' import 'https://static.xxx.com/lib/my-button/1.0.0/index.es.js' </script> <my-button size="large" @change="console.log">提交</my-button> -
验证与监控
用cypress-real-events测 Shadow DOM 内按钮点击;用performanceObserver测首次customElements.whenDefined('my-button')时长,接入公司 Sentry 大盘,超过 200 ms 自动报警。
拓展思考
- 微前端场景:qiankun 子应用如果也打成了 Web Component,就可以让主应用“零框架”运行,彻底摆脱 qiankun 的 JS 沙箱性能损耗;但此时需要把
__VUE_PROD_DEVTOOLS__关掉,防止 Vue -devtools 在子应用里重复注入。 - SSR 同构:Web Component 本身不支持服务端渲染,国内电商大促页面为了 SEO,会先用 Nuxt 把 Vue 组件渲染成静态字符串,再在客户端
hydrate阶段把同名标签升级为 Custom Element,实现“首屏直出 + 运行时隔离”。 - 设计系统落地:把 40+ 业务组件全部打成 Web Component 后,发现样式变量无法继承外部主题;阿里内部做法是借助
@vue/runtime-dom的useCssVars把 CSS 变量注入:host,然后在低代码平台提供“主题 JSON 转 CSS 变量”的在线工具,让运营同学拖拽即可换肤。