Skip to content

第三库的 ts 支持

第三方库有 ts 声明文件

如何查看第三方库有 ts 声明文件呢?你可以在 node_modules 中查看此库的源代码,若包 含了 xxx.d.ts 文件,则说明有 ts 声明文件。

我们可以在 tsconfig 中配置项:

json
{
  "compilerOptions": {
    "types": ["antd/es"] // 这里演示的antd,编译器则会在node_modules文件夹中查询此文件
  }
}
{
  "compilerOptions": {
    "types": ["antd/es"] // 这里演示的antd,编译器则会在node_modules文件夹中查询此文件
  }
}

第三方库无 ts 声明文件

​ 有些第三方库没有对应的 ts 声明文件,只能自己来声明。

默认导出

ts
// 声明 vue-img-cutter.d.ts
declare module "vue-img-cutter" {
  const content: typeof import("vue-img-cutter");
  export = content;
}
// 声明 vue-img-cutter.d.ts
declare module "vue-img-cutter" {
  const content: typeof import("vue-img-cutter");
  export = content;
}
js
// 使用
import ImgCutter from "vue-img-cutter";
// 使用
import ImgCutter from "vue-img-cutter";

按需导出

ts
// 声明 md-editor-v3.d.ts
declare module "md-editor-v3" {
  export const MdEditor: any;
  export const MdPreview: any;
}
// 声明 md-editor-v3.d.ts
declare module "md-editor-v3" {
  export const MdEditor: any;
  export const MdPreview: any;
}
js
// 使用
import { MdEditor } from "md-editor-v3";
// 使用
import { MdEditor } from "md-editor-v3";