记一次为js库开发声明文件的过程

背景

前段时间同事给我推了font-carrier 这个字体库,让我去开发一些字体工具。在使用这个库的过程中,发现这个库使用JavaScript开放,而我的项目用的是TypeScript,开发体验非常差。于是,我就萌生了为这个库添加类型的想法。

最后通过调研决定通过DefinitelyTyped实现。

什么是DefinitelyTyped

简单来说就是为那些使用纯js编写的库添加typescript类型的一种方式,例如React对应的@types/react。

所以为了font-carrier支持类型,就需要@types/font-carrier的声明库。

实现步骤

1 fork仓库

首先我们需要fork一份DefinitelyTyped的仓库,这样才能随意更改,当改完后再给他们提PR即可。

仓库地址:github.com/DefinitelyT...

2 拉取fork后的仓库

scss 复制代码
git clone [email protected]:zFitness/DefinitelyTyped.git

3 安装依赖

bash 复制代码
cd DefinitelyTyped
yarn

4 dts-gen安装

css 复制代码
npm i -g dts-gen

5 使用dts-gen创建目录

css 复制代码
npx dts-gen --dt --name font-carrier --template module

6 编写类型

这里有个注意事项,如果你的库是使用commonjs语法的导入导出,而不是es module的导入导出。

ini 复制代码
export = test
import test = require('')

参考文档: www.typescriptlang.org/docs/handbo...

下面是一些常用的写法转换:

导出一个对象

commonjs 导出一个对象时候:

ini 复制代码
const maxInterval = 12;
function getArrayLength(arr) {
  return arr.length;
}
module.exports = {
  getArrayLength,
  maxInterval,
};

写成ts:

arduino 复制代码
export function getArrayLength(arr: any[]): number;
export const maxInterval: 12;

导出正则表达式

javascript 复制代码
module.exports = /hello/

ts可以写成这样子

typescript 复制代码
declare const helloworld: RegExp;
export default helloworld;

导出数字

ini 复制代码
module.exports = 3.14

ts 可以写成如下:

typescript 复制代码
declare const PI:  number;
export default PI;

导出函数

CommonJS 中的一种导出方式是导出函数。因为函数也是对象,所以可以添加额外的字段并将其包含在导出中:

ini 复制代码
function getArrayLength(arr) {
  return arr.length;
}
getArrayLength.maxInterval = 12;
module.exports = getArrayLength

转换成ts如下:

arduino 复制代码
export default function(arr: any[]): number;
export const maxInterval: 12;

注意必须在 d.ts 中开启 esModuleInterop: true, 例如提交PR到Definitely Typed中的时候。这里可以使用export=来代替

typescript 复制代码
declare namespace getArrayLength {
  declare const maxInterval: 12;
}
declare function getArrayLength(arr: any[]): number;
export = getArrayLength;

7 发布测试

开发完后可以通过test命令进行测试。

bash 复制代码
npm test font-carrier

测试流程通过就可以提交代码,再提交一个PR,对方审核通过就会自动发布。

下面是我的提交PR:

github.com/DefinitelyT...

最后关于我编写的@types/font-carrier, 欢迎使用: www.npmjs.com/package/@ty...

参考资料

相关推荐
LaughingZhu5 分钟前
PH热榜 | 2025-04-09
前端·数据库·人工智能·mysql·开源
枫super17 分钟前
Day-03 前端 Web-Vue & Axios 基础
前端·javascript·vue.js
程序猿chen1 小时前
Vue.js组件安全工程化演进:从防御体系构建到安全性能融合
前端·vue.js·安全·面试·前端框架·跳槽·安全架构
你也来冲浪吗1 小时前
MD编辑器用法讲解
前端
小小小小宇1 小时前
十万字总结所有React hooks(含简单原理)
前端
MariaH1 小时前
MySQL数据库DQL
前端
Enjoy10241 小时前
v8垃圾回收机制
前端
Georgewu1 小时前
【HarmonyOS 5】敏感信息本地存储详解
前端·harmonyos
_Le_1 小时前
css 小师系列:一种新的影响样式优先级的方式😍
前端·css
wordbaby1 小时前
从前端视角看 MCP:解锁 LLM 工具调用与结构化交互
前端