如何在package.json中添加一个名为commit
的npm脚本:
"scripts": {
...
"commit": "node commit"
...
},
使用方法如下:
$> npm run commit patch "Your commit message goes here"
在这里,patch
可以替换为 minor
或 major
,具体取决于您想要的版本升级。
./commit.js
脚本的内容如下:
#!/usr/bin/env node
'use strict';
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const spawn = require('child_process').spawnSync;
async function version(versionType) {
const { stdout, stderr } = await exec(`npm version ${versionType} --no-git-tag-version --force`);
if (stderr) throw stderr;
return stdout;
}
async function branch() {
const { stdout, stderr } = await exec(`git rev-parse --abbrev-ref HEAD`);
if (stderr) throw stderr;
return stdout;
}
const run = async () => {
try {
const versionType = process.argv[2];
const gitMessage = process.argv[3];
if (versionType !== 'patch' && versionType !== 'minor' && versionType !== 'major') throw new Error('You need to specify npm version! [patch|minor|major]');
if (!gitMessage) throw new Error('You need to provide a git commit message!');
const npmVersion = await version(versionType);
await spawn('git', ['add', 'package.json', 'package-lock.json'], { stdio: 'inherit' });
await spawn('git', ['commit', '-m', gitMessage.trim()], { stdio: 'inherit' });
await spawn('git', ['tag', npmVersion.trim()], { stdio: 'inherit' });
await spawn('git', ['status'], { stdio: 'inherit' });
const currentBranch = await branch();
await spawn('git', ['push', 'origin', currentBranch.trim()], { stdio: 'inherit' });
} catch (err) {
console.log('Something went wrong:');
console.error(err.message);
console.error('\nPlease use this format: \nnpm run commit [patch|minor|major] "Commit message"');
}
};
run();
请注意,我没有添加
git add --all
,因为我更喜欢对我的提交进行更有选择性的操作,但是这个脚本的格式应该足够简单,以便任何人都可以理解并扩展。不过我确实使用了
git add package.json
,所以每次执行此脚本将至少更新
package.json
/
package-lock.json
的版本,并提交这些文件。我的策略是在执行上述命令之前先执行
git add
。
另一个需要考虑的问题是,这个脚本完全兼容
husky hooks
,特别是
pre-commit
,在我的情况下驱动了与
eslint
和
prettier
耦合的
lint-staged
。这样一来,所有东西都被漂亮地自动化、精简和标准化了。
希望这对某些人有所帮助,谢谢!