如何在 Vite 中配置 Vue 的编译选项(如 compilerOptions.isCustomElement)?

解读

面试官抛出这道题,核心想验证三件事:

  1. 你是否真正理解“Vite 只负责调度,Vue 的编译行为由 @vitejs/plugin-vue 决定”这一分工;
  2. 你是否知道国内 Vue3 项目 99% 会碰到“自定义元素白名单”场景(Web Components、第三方 UI 库标签、低代码平台标签等),而官方文档只给了“一句话”提示;
  3. 你能否把“配置”与“性能/兼容性”挂钩,体现出工程化思维,而不是只会抄官网。
    如果回答只停留在“在 vite.config.ts 里写 vue.compilerOptions”,只能拿 60 分;能把“运行时 vs 编译时”“SSR 复用”“插件顺序”“Monorepo 场景”讲清楚,才能拿到 90+。

知识点

  1. Vite 插件职责边界:@vitejs/plugin-vue 负责把 SFC 编译成 JS,真正调用的是 @vue/compiler-sfc;因此 Vue 的编译选项必须透传给该插件。
  2. 插件入口参数:plugin-vue 暴露一个 template 字段,其类型与 SFCTemplateCompileOptions 对齐,内部再透给 compiler-sfc。
  3. compilerOptions 与 runtimeOptions 区分:isCustomElement、whitespace、comments 等属于“编译时”行为,一旦配置错误,会导致运行时 hydration 失败或 TSX 类型报错。
  4. 国内常见坑:
    • 微前端/低代码平台大量自定义标签,必须动态正则匹配;
    • 使用 VitePress 或 Storybook 时,会二次加载 plugin-vue,配置需合并而非覆盖;
    • SSR 场景下,服务端与客户端的 compilerOptions 必须保持一致,否则出现 hydration mismatch。
  5. 插件顺序:若同时使用 vite-plugin-dts、unplugin-vue-components,务必把 plugin-vue 放在最前面,避免 AST 被提前修改导致 isCustomElement 失效。
  6. Monorepo 子包复用:把 compilerOptions 抽成 packages/shared/vue-compiler-options.ts,在 vite.config.ts 里统一引用,保证所有子项目一致。

答案

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

export default defineConfig({
  plugins: [
    vue({
      template: {
        compilerOptions: {
          // 1. 静态数组:适合标签集合固定
          // isCustomElement: tag => ['my-icon', 'my-chart'].includes(tag)

          // 2. 动态正则:国内低代码平台推荐
          isCustomElement: tag => /^my-|^app-|^x-/.test(tag)
        }
      }
    })
  ]
})

进阶写法(同时兼容 SSR 与 TSX):

import { resolve } from 'path'
const customElementRE = /^(my-|x-)/

export const sharedCompilerOptions = {
  isCustomElement: (tag: string) => customElementRE.test(tag)
} as const

// vite.config.ts
export default defineConfig({
  plugins: [vue({ template: { compilerOptions: sharedCompilerOptions } })],
  ssr: { external: ['@vue/compiler-dom'] } // 避免双实例
})

// tsconfig.json -> compilerOptions.types 里声明
"types": ["vite/client", "element-plus/global"]

验证方式:

  1. npm run build 后搜索编译产物,确认自定义标签未被解析成 createElementVNode("my-icon");
  2. 单元测试里用 @vue/test-utils 挂载带自定义标签的组件,断言 wrapper.find('my-icon').exists() 为 true;
  3. SSR 项目通过 curl 直出 HTML,确保服务端与客户端生成的 DOM 结构一致,无 hydration warning。

拓展思考

  1. 动态配置:把白名单维护在服务端接口,通过 loadEnv 拉取后注入,实现“热更新白名单”而无需重启 Vite。
  2. 微前端隔离:qiankun 子应用如果各自定义了 isCustomElement,需要在主应用通过 customElements.whenDefined 做二次校验,防止标签冲突。
  3. 与 Web Components 互转:当业务决定把 Vue 组件打包成原生自定义元素时,可用 vite-plugin-web-components 反向生成,并在主项目里把该元素从 isCustomElement 中剔除,避免循环解析。
  4. 性能权衡:滥用正则会导致每次编译都全量匹配,推荐把高频标签提前生成 Set,在 isCustomElement 里先做 O(1) 查找,再降级正则。
  5. 未来趋势:Vue 3.4 计划把 compilerOptions 抽成独立配置文件 vue.compiler.config.ts,Vite 侧只需 vue({ configFile: true }),可提前在团队规范里落地,降低升级成本。