likes
comments
collection
share

Typescript基础:如何更好的生成Typescript声明文件.d.ts

作者站长头像
站长
· 阅读数 13

背景

Typescript已经被前端广泛使用,如果你的项目还没有使用,建议赶紧使用起来,真的会对你的项目有足够的提升:

  • 让你的每个变量都有变量声明
  • 让你的每个方法找到其源头
  • 让你能提前使用一些超前的JavaScript语法,如:注解(装饰器)@controller 等语法糖

但是使用的过程也会带来一些痛苦,比如你要做一个js lib库,如果用Typescript 开发确实可以帮助其他者快速使用,但是如果你没有注意Typescript的声明文件规范,很容易出现以下使用情况:

// 会直接从src目录去寻找
import { IClient } from 'xxx-lib/src/client.d.ts'

// 而我们所期待的使用是
import { IClient} from 'xxx-lib'

所以我们需要学习一下,如何更好的生成我们的Typescript声明文件。

Typescript声明文件

声明文件:当使用第三方库时,我们需要引用它的声明文件,才能获得对应的代码补全、接口提示等功能。

从官网定义而言,声明文件.d.ts就是用来给IDE编辑器解析Typescript代码声明的地方。

学习声明

目前Typescript提供各种类型,我们常用的有以下几种:

  • declare var 声明全局变量,如:declare var jQuery: (selector: string) => any; ,我们就可以在全局中使用jQuery 变量而不会报错
  • declare function 声明全局方法
  • declare class 声明全局类
  • declare enum 声明全局枚举类型
  • declare namespace 声明(含有子属性的)全局对象
  • interface 和 type 声明全局类型

其中,declare基本上都根据Typescript 中会自动生成,而interfacetype则需要我们自己声明,自己使用。

生成声明文件

当你完成一个lib库开发,这个时候需要对外提供你声明文件,如:import foo from 'foo'

如果你需要对自己的npm包制作声明文件,具体有以下几个步骤:

  1. package.json中的typestypings ,如:"types":"dist/typings/index.d.ts"
  2. 在项目根目录创建typings ,新建一个index.d.ts 用来暴露你lib库相关的声明
  3. typescript.json配置文件中,添加入口,如:"includes":["./typings/index.d.ts"]

PS: typestypings 两者在package.json具有相同意义

package.json示例如下:

{
  "name": "@node-gptcommit/git-utils",
  "version": "1.0.0",
  "description": "关于git的一些工具函数",
  "main": "dist/index.js",
  "types": "./dist/typings/index.d.ts",
  "typings": "./dist/typings/index.d.ts",
  "type": "module",
  "scripts": {
    "build": "tsc -p tsconfig.release.json --outDir dist && cp -r typings dist"
  },
	"devDependencies": {
		"@types/node": "^16",
		"tslib": "^2.2.0",
		"typescript": "^4.7.2"
	},
  "dependencies": {
    "simple-git": "^3.17.0"
  },
  "author": "qborfy",
  "license": "MIT"
}

typescript.json 示例如下:

{
  "include": [
    "src/*",
    "typings/index.d.ts"
  ],
  "compilerOptions": {
    "baseUrl": ".",
    "rootDir": ".",
    "target": "ES2019",
    "module": "ESNext",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true,
    "noImplicitOverride": true,
    "noUnusedLocals": true,
    "useUnknownInCatchVariables": false,
    "declaration": true,
    "declarationDir": "dist"
  },
  "exclude": ["node_modules"]
}

index.d.ts实现

前面基本知道Typescript声明和如何在package.json标注好当前npm包会使用哪个声明文件,那么接下来,我们应该如何一个index.d.ts,主要靠以下几个:

  • export 导出变量
  • export namespace 导出(含有子属性的)对象
  • export default ES6 默认导出
  • export = commonjs 导出模块

PS: 只有只有 functionclass和 interface 支持export default

index.d.ts示范:

// index.d.ts
// 将src中的声明文件引入过来
export * from '../src/index';

// 导出声明的函数
export declare function bar(): string;

使用demo.js示范:

//demo.js
// 使用就如下 bar就是一个函数
import { bar } from 'libs'
bar();

发布

发布声明文件一般有两种做法:

  • 一种是发布到@types/xxx ,在types目录下新建一个package.json去维护,不推荐
  • 另外一种是和npm包一起发布,目前基本上大多数都采用这种,本文也使用采用这种

参考资料