You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Cypress自定义命令封装为NPM包并解决发布异常

如何将Cypress自定义命令打包为可复用NPM包

一、调整编译配置与代码结构

1. 修改tsconfig.json适配NPM包编译

需要新增输出目录、类型声明生成等配置,确保编译产物符合NPM包规范:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "lib": ["dom", "es6"],
    "types": ["cypress", "node", "cypress-xpath"],
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    // 指定编译产物输出目录
    "outDir": "./dist",
    // 生成TypeScript类型声明文件(供其他TS项目引用)
    "declaration": true,
    "declarationMap": true
  },
  "include": ["src/**/*"], // 假设代码存放在src目录,按需调整
  "exclude": ["node_modules", "dist"]
}

2. 修正代码导入路径与注释(中文翻译版)

commands.ts

// commands.ts
import { whateverClass1 } from "..";
import { whateverClass2 } from "..";

// 扩展Cypress全局命令的类型声明,让TS识别自定义命令
declare global {
  namespace Cypress {
    interface Chainable {
      createLabel: typeof createLabel;
      save : typeof save ;
    }
  }
}

// 自定义命令:创建标签
const createLabel = (param: string) => {
  whateverClass1.createLabel(param);
};

// 自定义命令:执行保存操作
const save = () => {
  whateverClass2.save();
};

const Commands = {
  save,
  createLabel,
};
export default Commands;

e2e.ts

// e2e.ts
// 导入自定义命令集合
import Commands from './commands';

// 将自定义命令挂载到Cypress全局cy对象
Cypress.Commands.add('save', Commands.save);
Cypress.Commands.add('createLabel', Commands.createLabel);

二、配置package.json关键字段

这是NPM包发布的核心配置,需确保必填字段完整:

{
  "name": "your-unique-package-name", // 包名必须在npm官网唯一,提前搜索确认
  "version": "1.0.0",
  "main": "./dist/commands.js", // 编译后的JS入口文件路径
  "types": "./dist/commands.d.ts", // 类型声明文件路径
  "files": [
    "dist/**/*" // 指定要发布的文件范围,只传编译产物
  ],
  "scripts": {
    "build": "tsc", // 编译命令
    "prepublishOnly": "npm run build" // 发布前自动执行编译,确保产物最新
  },
  "peerDependencies": {
    "cypress": "^10.0.0" // 声明依赖的Cypress版本范围,避免重复安装
  },
  "devDependencies": {
    "typescript": "^5.0.0",
    "cypress": "^13.0.0",
    "cypress-xpath": "^2.0.0"
  }
}

三、解决npm publish 404错误&完成发布

1. 排查404原因

  • 包名重复:去npm官网搜索你的包名,若已存在需改名
  • 源地址错误:如果使用了私有npm源,切换回官方源:npm config set registry https://registry.npmjs.org/
  • 未登录/权限不足:执行npm whoami确认已登录正确账号;若为组织包,确保账号拥有组织发布权限

2. 发布流程

  1. 安装依赖:npm install
  2. 编译代码:npm run build
  3. 登录npm:npm login(按提示输入账号密码)
  4. 发布包:npm publish

内容的提问来源于stack exchange,提问作者CIC92

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 14:05:30