如何为新插件编写 TypeScript 声明文件并发布到 @types?

解读

国内一线团队已将 TypeScript 作为前端基建的“硬通货”。面试官抛出此题,既考察你对 Gulp 插件生态 的熟悉度,也验证你是否能把“声明文件 → 测试 → 发包”这一链路跑通。回答时务必体现三点:

  1. 声明文件必须符合 Gulp 官方类型规范(依赖 vinyl 与 undertaker 的泛型约束);
  2. 发包路径选择 @types 还是 插件自带 types,要给出权衡;
  3. 国内网络环境下,如何绕过 npm 镜像缓存与 DefinitelyTyped 审核卡点。

知识点

  • Gulp 插件本质:Transform Stream(Node.js Duplex)的再包装,输入输出都是 Vinyl 对象。
  • 声明文件入口:index.d.ts 必须暴露 declare function gulpFoo(options?: Options): NodeJS.ReadWriteStream;,并同步导出 Options 接口。
  • 依赖注入:用 /// <reference types="node" /> 与 import * as Vinyl from 'vinyl'; 解决类型链路。
  • 三斜杠指令 vs moduleResolution:国内项目多强制 "moduleResolution": "node",必须 显式依赖 @types/node 否则 CI 会报 Cannot find name 'Buffer'。
  • 发包策略:
    – 插件仓库自带 types 字段:维护简单,版本锁死,适合公司私有 npm;
    – 提交到 DefinitelyTyped(即 @types/gulp-foo):社区共享,需通过 dtslint 校验,国内贡献者需配置 git config core.autocrlf false 避免 LF 校验失败。
  • 国内加速:pnpm dlx dts-gen --dt 生成脚手架后,用 npmmirror.com 镜像安装依赖,再 pnpm test 跑通 dtslint;提交 PR 时附上中文 commit message 会被机器人警告,必须全英文。

答案

  1. 本地验证插件 API
    在插件根目录执行 npm link,新建一个 TypeScript 空项目,tsconfig.json 开启 "strict": true,手写调用代码:

    import foo = require('gulp-foo');
    gulp.src('src/*.png')
        .pipe(foo({ quality: 80 }))
        .pipe(gulp.dest('dist'));
    

    若 tsc 无报错,说明 API 已稳定,可以开始写声明。

  2. 编写 index.d.ts
    文件必须放在插件仓库的 types/index.d.ts,内容模板:

    /// <reference types="node" />
    import { Transform } from 'stream';
    export interface Options {
        quality?: number;
    }
    declare function gulpFoo(options?: Options): Transform;
    export = gulpFoo;
    

    关键点:

    • 返回类型用 Transform 而不是 NodeJS.ReadWriteStream,否则 VSCode 智能提示会丢失 pipe 链式提示。
    • 若插件支持 Gulp 4 的 series/parallel,再额外导出 namespace gulpFoo 并挂载 displayName 属性。
  3. 单元测试
    在 types/gulp-foo-tests.ts 中把 所有重载 跑一遍:

    import foo = require('gulp-foo');
    foo();                // $ExpectType Transform
    foo({ quality: 90 }); // $ExpectType Transform
    

    执行 npx dtslint types 零警告方可进入下一步。

  4. 选择发包路径

    • 公司私有 npm:把 "types": "types/index.d.ts" 写进插件 package.json,随插件版本一起发布,无需审核,国内网络友好。
    • 社区共享:fork DefinitelyTyped,目录结构 types/gulp-foo/index.d.ts,运行 pnpm dtslint 后提交 PR,标题格式 “[@types/gulp-foo] Add new package”,body 里贴 npm 包首页 与 下载量截图(国内可用 npmmirror.com 数据),加速合并。
  5. 国内加速技巧

    • 设置 npm config set @types:registry https://registry.npmmirror.com 避免官方源 443 超时。
    • PR 合并后,@types/gulp-foo 约 30 分钟同步到国内镜像,CI 若仍提示找不到类型,可临时 "skipLibCheck": true 过渡。

拓展思考

  • Monorepo 场景:若插件与主库同仓,用 project references 把 types/tsconfig.json 独立出来,防止路径别名污染。
  • 流式泛型增强:借助 vinyl@3 的 Vinyl.BufferFile 泛型,可让声明文件做到 “输入 PNG,输出 PNG” 级精确提示,提升大型项目重构安全。
  • 国内合规:若插件涉及 图像处理底层二进制,声明文件里不要暴露 sharp 的 libvips 路径,否则企业私有仓库扫描会报 “敏感路径泄露” 合规风险。