Skip to content

vue 全局组件的 ts 类型提示

定义的全局组件、安装的组件库没有 TS 类型提示?试试这个!

组件库

若下载的组件库全局安装在项目里了,但是没有 TS 支持,组件的类型都显示 any。

解决步骤:

  1. 查看组件库包文件根目录中是否有xxx.d.ts类型声明文件
  2. 若有类型声明文件只需在 ts.config.json 中配置types:[包文件名/xxx.d.ts]即可享有组件库的 TS 类型支持。

自己封装的组件

若自己封装的全局组件需要编译器类型提示,只需要在项目根文件中创建components.d.ts文件

ts
// components.d.ts
import Button from "./Button/index.vue";
declare module "@vue/runtime-core" {
  export interface GlobalComponents {
    DemoButton: typeof Button;
  }
}
export {};
// components.d.ts
import Button from "./Button/index.vue";
declare module "@vue/runtime-core" {
  export interface GlobalComponents {
    DemoButton: typeof Button;
  }
}
export {};

ts
// global.d.ts
import Button from "./Button/index.vue";
declare module "vue" {
  export interface GlobalComponents {
    DemoButton: typeof Button;
  }
}
// global.d.ts
import Button from "./Button/index.vue";
declare module "vue" {
  export interface GlobalComponents {
    DemoButton: typeof Button;
  }
}

参考

  1. 全局组件类型声明
  2. 全局组件类型声明的最佳实践 (Vue3+TS+Volar) - 掘金 (juejin.cn)