如何生成 d.ts 并自动发布到 npm?
解读
面试官真正想考察的是“把 TypeScript 声明文件(d.ts)作为产物,持续、可靠、可回滚地交付到 npm”的完整链路。国内一线团队普遍要求:
- 本地零配置即可生成与源码版本一一对应的声明文件;
- 构建过程完全由 Gulp 驱动,不依赖开发者手动
tsc; - 发布环节自动 bump 版本、打 tag、回滚、同步到公司私有源,并符合国内网络环境(淘宝源、cnpm、verdaccio 等);
- 产物目录干净,只发布
dist+d.ts,不把 devDependencies 的臃肿体积带到线上。
知识点
- Vinyl 流与 gulp.src/gulp.dest:保证 d.ts 生成后仍走同一套管道,避免磁盘 I/O 抖动。
- gulp-typescript / gulp-dts-generator:在内存中一次性完成 JS + d.ts 编译,sourcemap 与声明文件同目录输出。
- gulp-better-rollup + @rollup/plugin-typescript:当项目为“库模式”时,用 Rollup 树摇并生成单一 d.ts 入口,减少冗余模块声明。
- gulp-conventional-changelog + gulp-bump:基于 Angular Commit 规范自动计算 semver,杜绝人为拍脑袋升版。
- gulp-shell / gulp-exec:在流末尾调用
npm publish或cnpm publish,自动切换 registry(官方源/私有源)。 - gulp-git:tag 与 commit 同步,支持回滚到任意 tag。
- npm token 与 GitHub Actions(或 GitLab CI):国内团队常用 self-hosted runner + 内网 verdaccio,token 通过 Vault/阿里云 KMS 注入,防止泄漏。
- .npmignore vs files 字段:优先用
files:["dist","types"]白名单,避免把 gulpfile、test、src 发到 npm。 - 双因子认证(2FA):国内公有库已强制开启,CI 中需用 automation token 绕过一次性口令。
答案
下面给出一条可直接落地的 Gulp 任务链,覆盖“编译→测试→版本→发布”四阶段,全部任务写在 gulpfile.ts 中,开发者只需执行 gulp release 即可一键发版。
import { src, dest, series, parallel } from 'gulp';
import ts from 'gulp-typescript';
import rename from 'gulp-rename';
import bump from 'gulp-bump';
import conventionalChangelog from 'gulp-conventional-changelog';
import git from 'gulp-git';
import shell from 'gulp-shell';
import { readFileSync } from 'fs';
const proj = ts.createProject('tsconfig.json', { declaration: true, outDir: 'dist' });
// 1. 编译并生成 d.ts
function compile() {
return proj.src()
.pipe(proj()) // 同时产出 js 与 d.ts
.pipe(dest('dist')); // 统一落到 dist
}
// 2. 跑单测(示例用 jest)
function test() {
return shell.task('npm run test -- --passWithNoTests')();
}
// 3. 自动 bump 版本
function bumpVersion(cb: Function) {
return src(['./package.json'])
.pipe(bump({ type: process.argv.includes('--patch') ? 'patch' : 'minor' }))
.pipe(dest('./'))
.on('end', cb);
}
// 4. 生成 changelog
function changelog(cb: Function) {
return src('CHANGELOG.md', { allowEmpty: true })
.pipe(conventionalChangelog({ preset: 'angular' }))
.pipe(dest('./'))
.on('end', cb);
}
// 5. 提交 & 打 tag
function commitAndTag(cb: Function) {
const pkg = JSON.parse(readFileSync('./package.json', 'utf8'));
const tag = `v${pkg.version}`;
return src('.')
.pipe(git.add())
.pipe(git.commit(`chore: release ${tag}`))
.on('end', () => {
git.tag(tag, `release ${tag}`, cb);
});
}
// 6. 发布到 npm(国内私有源示例)
function publish() {
const registry = process.env.NPM_REGISTRY || 'https://registry.npmjs.org';
return shell.task(`npm publish --registry=${registry}`)();
}
// 7. 把 tag 推到远端
function push(cb: Function) {
git.push('origin', 'master', { args: '--tags' }, cb);
}
// 8. 组合任务
export const build = series(compile);
export const release = series(
build,
test,
bumpVersion,
changelog,
commitAndTag,
publish,
push
);
使用方式:
# 本地一次性发 minor 版本
gulp release
# 紧急补丁
gulp release --patch
关键配置补充:
tsconfig.json中"declaration": true与"declarationMap": true必须开启,确保 d.ts 与 d.ts.map 同时生成;package.json里"types": "dist/index.d.ts"与"files": ["dist"]配合使用,npm 包体积控制在最小;- CI 环境变量提前注入
NPM_TOKEN与NPM_REGISTRY,**国内私有源地址如 https://npm.xxx-inc.com**; - 若项目为 monorepo,可在
compile任务里用lerna exec --scope=foo -- gulp compile做子包隔离,防止 d.ts 交叉污染。
拓展思考
- 双轨产物:如果库同时支持 CommonJS 与 ESM,可让 Gulp 分别输出
dist/cjs与dist/esm,并在 d.ts 入口使用exports字段映射,保证 Node12+ 的 Conditional Exports 严格匹配。 - 增量编译:在大型代码库中启用
gulp-cache与gulp-newer,只让变更文件重新生成 d.ts,CI 构建时长可从 3min 降到 30s。 - API Extractor 校验:微软官方工具可扫描 d.ts 的公共 API 漂移,在
prepublishOnly钩子中自动阻断不合规发布,避免“breaking change 误发 patch”。 - 回滚策略:在
publish任务后自动写入publish-state.json到 OSS,包含版本、SHA、时间戳,一旦线上故障可gulp rollback --version=x.x.x秒级回退。 - 国内加速:若公司使用 Verdaccio + cnpm 混合源,可在
publish任务后同步执行cnpm sync <pkg>,保证淘宝镜像 5min 内更新,降低下游安装失败率。
掌握以上链路,你不仅能在面试中把“生成 d.ts 并自动发布到 npm”讲得滴水不漏,还能让面试官感受到你对国内网络、企业合规、CI/CD、回滚容灾的实战深度。