如何发布一个 npm 库,自动化管理版本号、生成 changelog、tag 等

790 阅读2分钟

1. npm 发布

若没有登录,npm login,输入npm的账号,密码,邮箱。 npm publish发布,若是没有登录会提示

image.png

2. release-it是什么

用于自动化版本控制和包发布相关任务的通用CLI工具:

  • Bump版本(例如package.json)
  • Git提交、标记、推送
  • 使用钩子执行任何(测试或构建)命令
  • 在GitHub或GitLab上创建版本
  • 生成变更日志
  • 发布到npm
  • 管理预发布
  • 使用插件扩展
  • 从任何CI/CD环境中发布

2.1 npm init release-it 怎么安装release-it包的

  • 安装release-it,运行npm init release-it
npm init release-it
  • npm init命令原理, npm init release-it会转换成 npx create-release-it
npm init <package-spec> (same as `npx <package-spec>)
npm init <@scope> (same as `npx <@scope>/create`) aliases: create, innit

image.png

2.2 change-log git-commit

安装 changelog 插件,`npm i @release-it/conventional-changelog -D`

image.png

  • 添加配置到.release-it.json
{
  "github": {
    "release": false
  },
  "git": {
    "commitMessage": "release: v${version}"
  },
  "npm": {
    "publish": false
  },
  "hooks": {
    "after:bump": "echo 更新版本成功"
  },
  "plugins": {
    "@release-it/conventional-changelog": {
      "preset": "angular",
      "infile": "CHANGELOG.md"
    }
  }
}
  • 在package.json里配置命令,运行 npm run release
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "release": "release-it",
    "commit": "git-cz"
  },

2.3 关于发布版本介绍

image.png

3. release-it原理

  • 获取name,version和changelog
const reduceUntil = async (collection, fn) => {
  let result;
  for (const item of collection) {
    if (result) break;
    result = await fn(item);
  }
  return result;
};
  const name = await reduceUntil(plugins, plugin => plugin.getName());
    const latestVersion = (await reduceUntil(plugins, plugin => plugin.getLatestVersion())) || '0.0.0';
    const changelog = await reduceUntil(plugins, plugin => plugin.getChangelog(latestVersion));
    
  • git 钩子实际执行下面的代码,如git commit, git tag,git push
  async release() {
    const { commit, tag, push } = this.options;
    await this.step({ enabled: commit, task: () => this.commit(), label: 'Git commit', prompt: 'commit' });
    await this.step({ enabled: tag, task: () => this.tag(), label: 'Git tag', prompt: 'tag' });
    return !!(await this.step({ enabled: push, task: () => this.push(), label: 'Git push', prompt: 'push' }));
  }

4. 小结

release-it帮助我们解决版本发布的问题,解放我们的双手,增加摸鱼时间