yarn bump自动升级package.json里的版本号

726 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

  • zx是一个很棒的谷歌出品的js库,能够很方便地执行shell命令,可以通过yarn global add zx来安装
  • prompts是一个用于命令行交互的的库,Vite也用了它

由于部署完之后,希望通过版本号,来判断拿到的是最新代码,还是缓存。 所以经常会需要手动修改package.json里的版本号、手动git tag打标签。 最近终于工作不忙,有时间把这个自动升版本号的脚本,从原本的js改成采用zx。

注:当前代码在Mac系统,能按预期工作。Windows系统好存在BUG,待修复

  1. 新建bump.mjs文件,内容如下:
#!/usr/bin/env zx
/**
 * * 自动升级版本号并打标签 *
 * 相当于修改package.json里面version字段值,然后git commit -m 'xxx',再git tag -a ${version}
 * */
 
// https://github.com/google/zx
import 'zx/globals'
const filename = './package.json'
const { version } = require(filename)
const prompts = require('prompts')
 
console.log(chalk.blue('Long long ago, there is a tiger.'))
console.log('Current version: ' + version)
 
const [major, minor, patch] = version.split('.')
const nextMajor = String(Number(major) + 1) + '.0.0'
const nextMinor = major + '.' + String(Number(minor) + 1) + '.0'
const nextPatch = major + '.' + minor + '.' + String(Number(patch) + 1)
 
const questions = [
  {
    type: 'text',
    name: 'dish',
    message: 'Would you like some cocktail? ',
  },
  {
    type: 'select',
    name: 'version',
    message: 'Which part do you want to bump? ',
    choices: [
      { title: 'patch: ' + nextPatch, value: nextPatch },
      { title: 'minor: ' + nextMinor, value: nextMinor },
      { title: 'major: ' + nextMajor, value: nextMajor },
    ],
  },
  {
    type: prev => prev && 'confirm',
    name: 'commit',
    message: '是否执行git commit提交代码?',
    initial: true,
  },
  {
    type: prev => prev && 'text',
    name: 'message',
    message: "git commit的内容(留空则使用'Bump version'):",
  },
  {
    type: prev => (prev || prev === '') && 'confirm',
    name: 'tag',
    message: '是否执行git tag打标签?',
    initial: true,
  },
]
 
const response = await prompts(questions)
const newVersion = response.version
if (newVersion) {
  const data = await fs.readFile(filename)
  const content = String(data).replace(`"version": "${version}"`, `"version": "${newVersion}"`)
  await fs.writeFile(filename, content)
  console.log(chalk.green('`package.json` updated!'))
}
if (response.commit) {
  let message = response.message
  if (message === '') {
    message = `Bump version: ${version}${newVersion}`
  }
  if (message) {
    // console.log(`git add . && git commit -m '${message}'`)
    await $`git add . && git commit -m ${message}`
    if (response.tag) {
      const tag = 'v' + newVersion
      // console.log(`git tag -a ${tag} -m ''`)
      await $`git tag -a ${tag} -m ''`
      await $`git push && git push --tags`
    }
  } else {
    // message === undefined的情况
    console.log(chalk.yellow('I can see the first leaf falling.'))
  }
}
  1. 添加依赖
yarn add --dev zx prompts
  1. 自定义bump命令,修改package.json文件,增加这一行:
{
  ...
  "scripts": {
    "bump": "zx bump.mjs",
    ...
  },
  ...
}

OK, 现在可以很愉快地使用yarn bump来升版本号和打标签了~