如何为插件添加 TypeScript 声明并发布到 npm?
解读
在国内前端面试中,Cypress 插件开发能力已成为高级测试工程师与前端架构师的分水岭。面试官通过此题考察三点:
- 是否理解 Cypress 的插件注入机制(
cypress.config.ts中的setupNodeEvents) - 能否为社区补齐类型安全这一环,体现对 TS 生态的贡献意识
- 是否熟悉 npm 发布合规流程,尤其在国内网络环境下如何镜像加速与二步验证
若仅回答“写个 .d.ts 然后 npm publish”,会被视为初级认知;必须覆盖模块声明合并、版本对齐、国内源切换与持续集成等工程细节,才能拿到高分。
知识点
-
Cypress 插件类型体系
Cypress.PluginConfig:Node 侧事件钩子类型Cypress.CommandFn:自定义命令类型- 模块扩充路径:
cypress/support/index.ts与cypress/global.d.ts的三斜线指令优先级
-
声明文件四种输出策略
- 与源码同仓库:
types/index.d.ts+package.json的types字段 - DefinitelyTyped 托管:
@types/cypress-xxx(国内镜像同步延迟约 2h) - 子路径导出:
exports["./plugin"]与typesVersions映射 - 生成器方案:
tsc --declaration结合rollup-plugin-dts做扁平化
- 与源码同仓库:
-
npm 发布合规
- 国内镜像源切换:
npx np --no-cleanup --registry=https://registry.npmmirror.com - 二步验证:
npm profile enable-2fa auth-only解决手机收不到 OTP 问题 - 文件白名单:
package.json的files字段排除cypress/videos等大块头
- 国内镜像源切换:
-
CI 集成
- GitHub Actions 走
pnpm缓存,Node 16 镜像阿里云加速 - 使用
changeset做语义化版本与changelog双语输出,方便国内文档站搬运
- GitHub Actions 走
答案
步骤一:搭建插件仓库
mkdir cypress-plugin-logger && cd $_
pnpm init
pnpm add -D cypress typescript @types/node rollup rollup-plugin-dts
在 tsconfig.build.json 中开启 "declaration": true 与 "outDir": "dist",确保隔离测试代码。
步骤二:编写插件源码
src/index.ts
import { PluginConfig } from 'cypress'
export const loggerPlugin: PluginConfig = (on, config) => {
on('task', {
log(message: string) {
console.log(`[CY] ${message}`)
return null
}
})
}
关键点:导出函数而非默认导出,方便具名导入与 tree-shaking。
步骤三:生成声明文件
rollup.config.mjs
import dts from 'rollup-plugin-dts'
export default {
input: 'src/index.ts',
output: { file: 'dist/index.d.ts', format: 'es' },
plugins: [dts()]
}
执行 pnpm build:dts 后,得到单文件声明,避免路径黑洞。
步骤四:模块合并与全局扩充
types/cypress.d.ts
/// <reference types="cypress" />
declare namespace Cypress {
interface Chainable {
logToTask(message: string): Chainable<void>
}
}
在 support/index.ts 中
Cypress.Commands.add('logToTask', (msg) => {
cy.task('log', msg)
})
通过同名接口自动合并,实现类型提示。
步骤五:package.json 合规配置
{
"name": "cypress-plugin-logger",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"typesVersions": {
">=4.5": { "*": ["dist/*"] }
},
"files": ["dist", "types"],
"publishConfig": {
"registry": "https://registry.npmjs.org",
"access": "public"
}
}
files 白名单防止把 cypress/screenshots 传上去,节省 tarball 体积。
步骤六:本地验证
npx cypress open --config-file cypress.config.ts
在 cypress.config.ts 中
import { defineConfig } from 'cypress'
import { loggerPlugin } from 'cypress-plugin-logger'
export default defineConfig({
e2e: {
setupNodeEvents(on, config) {
loggerPlugin(on, config)
return config
}
}
})
确保类型无红、任务可调用,再进入发布流程。
步骤七:发布到 npm
- 国内先切换源加速安装:
npx publish-to-npm-cli --registry https://registry.npmmirror.com - 登录主 registry:
npm login --registry https://registry.npmjs.org - 二步验证:
npm publish --otp=$(node scripts/get-otp.js) - 同步到淘宝镜像:
curl -X PUT https://npmmirror.com/sync/cypress-plugin-logger - 打 GitHub Release,附中英双语 changelog,方便国内博客二次传播。
步骤八:持续集成
.github/workflows/release.yml
on:
push:
tags: ["v*"]
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v2
with:
version: 8
run_install: true
- run: pnpm build
- run: npx changeset publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
使用 changeset 自动** bump 版本与生成 changelog**,降低人工失误。
拓展思考
- Monorepo 场景:若插件与业务测试代码同仓库,可用
pnpm workspaces把types作为独立包,防止循环依赖导致类型爆炸。 - 国内私有源:企业内网 Nexus 需上传
.d.ts文件,否则 TS 会回退到any,失去静态检查意义;可在ci.yml里加npm publish --registry=http://nexus.xxx.com/repository/npm-hosted/。 - Cypress 11 联邦模块:未来插件可能以
import('cypress/plugin')形式异步加载,需要把types拆成异步声明文件index.d.mts,提前布局可避免重大版本断档。