全局组件类型声明的最佳实践 (Vue3+TS+Volar)

11,516 阅读2分钟

前言

  • 阅读本文您可以收获🔑:给全局组件添加类型声明的最佳实践(Vue3+TS+Volar)
  • 2022.2.7,农历大年初七,Vue3成为官方默认版本,这意味着,不管你学不学,Vue4已经在路上(狗头)。趁着过年闲着,悄悄地自家的UI组件库重写成Vue3,并且成功全局安装使用。

遇到问题

  • 不知道如何给UI组件库(自定义全局组件)声明类型,并且Vue3最新的官方文档,也找不到关于全局组件类型声明的一丝痕迹,因此,UI组件使用的时候也就没有任何的提示

  • demo1.png

实践方案

  • 问题原因:Vue3并没有对自定义全局组件做TS类型支持处理,而是把这个功能转交Volar实现
  • 实现原理:利用TypeScript模块扩充技术,对全局组件的类型进行扩充,从而实现对新注册全局组件的类型保护
  • 实现步骤:①声明一个的*d.ts类型文件 ②对类型接口进行类型模块扩充并导出
  • 三种实现方式的(核心代码):
  1. 🧨🧨(最佳实践)参考Volar文档 定义全局组件:使用GlobalComponents类型接口声明类型
// components.d.ts
import Button from './Button/index.vue';
declare module '@vue/runtime-core' {
  export interface GlobalComponents {
    DemoButton: typeof Button;
  }
}
export {};

简评:推荐,同时也是Volar官方全局组件的推荐写法,基于Volar,必须安装该插件,GlobalComponents是Volar专门为了解决全局组件类型而新增的类型接口

  1. 参考element-plusUI库源码 声明全局组件类型
// global.d.ts
import Button from './Button/index.vue';
declare module 'vue' {
  export interface GlobalComponents {
    DemoButton: typeof Button;
  }
}

简评:和方式1基本一样,不同的是声明需要扩充的模块是'vue',但是Volar内部源码作了兼容处理,还是建议使用方式1

  1. 参考Vue3文档 声明全局属性类型 简评:可以实现但不推荐,ComponentCustomProperties设计用于声明全局属性类型,而不是全局组件类型
// components.d.ts
import Button from './Button/index.vue';
declare module 'vue' {
  interface ComponentCustomProperties {
    DemoButton: typeof Button;
  }
}

结果

  • 借助Volar的GlobalComponents类型接口,成功添加类型提示,又可以开心愉快的玩耍了,ts+script setup真香~
  • demo2.png