注意:husky 的版本大于6.x版本,需要采用新的方式。不兼容之前的写法。
npm install -D husky
{
"scripts": {
"prepare": "husky install"
}
}
npx husky add .husky/pre-commit “npm run package_version_auto_add”
{
"name": "app01",
"version": "1.1.3",
"description": "",
"main": "index.js",
"scripts": {
"prepare": "husky install",
"package_version_auto_add": "node package_version_auto_add.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"husky": "^7.0.4"
}
}
const execSync = require('child_process').execSync
const path = require('path')
const fs = require('fs')
console.log('------------ 开发自动升级package.json版本号 ------------');
const projectPath = path.join(__dirname, './')
const packageJsonStr = fs.readFileSync('./package.json').toString()
try {
const packageJson = JSON.parse(packageJsonStr)
// 升级版本号
const arr = packageJson.version.split('.')
if (arr[2] < 9) {
arr[2] = +arr[2] + 1
} else if (arr[1] < 9) {
arr[1] = +arr[1] + 1
arr[2] = 0
} else {
arr[0] = +arr[0] + 1
arr[1] = 0
arr[2] = 0
}
const newVersion = arr.join('.')
packageJson.version = newVersion
console.log(packageJson);
fs.writeFileSync('./package.json', JSON.stringify(packageJson, null, '\t'))
// add new package.json
execSync(`git add package.json`)
} catch (e) {
console.error('处理package.json失败,请重试', e.message);
process.exit(1)
}
https://www.npmjs.com/package/husky
https://typicode.github.io/husky/#/
https://zhuanlan.zhihu.com/p/366786798