Appearance
vue 全局组件的 ts 类型提示
定义的全局组件、安装的组件库没有 TS 类型提示?试试这个!
组件库
若下载的组件库全局安装在项目里了,但是没有 TS 支持,组件的类型都显示 any。
解决步骤:
- 查看组件库包文件根目录中是否有
xxx.d.ts
类型声明文件 - 若有类型声明文件只需在 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;
}
}