ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

自动化版本更新与 npm 包一键发布脚本

自动化版本更新与 npm 包一键发布脚本 自动化版本更新与 npm 包一键发布脚本在维护开源 CLI 工具或前端组件库时“版本发布Release Process”如果全靠人工手动操作往往是一场充满低级失误的折磨忘记修改package.json的版本号手动写CHANGELOG.md漏掉了几个重要的 PR 变更忘记给 Git 提交打对应的git tag在本地未完成构建、存在编译错误的情况下手滑执行了npm publish导致发布了一个损坏的坏包。通过将版本自增、Changelog 提取、Git 提交打标与 npm 发布封装为一个完全自动化的交互式发布脚本一分钟内就能零失误完成标准语义化发版。自动化发版流水线的六步闭环[ 运行 pnpm release ] │ ▼ (第一步: 本地环境干净度检查与全量单测) [ git status 检查 全量测试 (Vitest) ] │ ▼ (第二步: 交互式选择新版本号) [ Patch (0.9.1) / Minor (0.10.0) / Major (1.0.0) ] │ ▼ (第三步: 自动化更新 package.json 生成 Changelog) [ Conventional Commits 自动提取变更日志 ] │ ▼ (第四步: 生产干净编译打包) [ 执行 pnpm build 构建最新二进制/JS产物 ] │ ▼ (第五步: Git 自动提交并打 Tag) [ git commit -m chore(release): vX.Y.Z git tag vX.Y.Z ] │ ▼ (第六步: 一键推送与发布) [ git push --follow-tags npm publish ]50 行发布脚本实现scripts/release.tsimport { execSync } from node:child_process; import { readFileSync, writeFileSync } from node:fs; import prompts from prompts; import semver from semver; function run(cmd: string) { console.log(\x1b[36m$ ${cmd}\x1b[0m); execSync(cmd, { stdio: inherit }); } export async function release() { // 1. 检查 Git 工作区是否干净 const status execSync(git status --porcelain).toString().trim(); if (status) { console.error(❌ Git 工作区存在未提交的修改请先提交或 stash 后再执行发版); process.exit(1); } // 2. 运行全量单测 console.log(\n 正在运行发版前全量单元测试...); run(pnpm test); // 3. 读取当前版本号并计算候选版本 const pkg JSON.parse(readFileSync(package.json, utf-8)); const currentVersion pkg.version; const response await prompts({ type: select, name: version, message: 当前版本为 v${currentVersion}请选择要发布的版本:, choices: [ { title: Patch (${semver.inc(currentVersion, patch)}) - 小修补, value: semver.inc(currentVersion, patch) }, { title: Minor (${semver.inc(currentVersion, minor)}) - 新特性, value: semver.inc(currentVersion, minor) }, { title: Major (${semver.inc(currentVersion, major)}) - 重大重构, value: semver.inc(currentVersion, major) }, ], }); const targetVersion response.version; if (!targetVersion) return; // 4. 更新 package.json pkg.version targetVersion; writeFileSync(package.json, JSON.stringify(pkg, null, 2) \n); // 5. 执行干净生产编译 console.log(\n 正在执行生产打包...); run(pnpm build); // 6. Git 提交并打标 run(git add package.json); run(git commit -m chore(release): v${targetVersion}); run(git tag v${targetVersion}); run(git push origin main --tags); // 7. 发布至 npm run(npm publish --access public); console.log(\n 版本 v${targetVersion} 发布成功); } release().catch(console.error);关键细节与避坑点必须在发版前强制跑测试将pnpm test作为发版的第一道硬门禁只要有一个测试用例失败脚本立即终止绝不允许带病发版使用--access public对于 Scope 包如star/clinpm 默认会当作私有包拦截必须显式指定公开访问权限。总结把重复易错的事情交给自动化脚本是工程师对自己最好的善待。一键发版让每一次版本交付都从容而优雅。
返回列表