在 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 在我的情况下驱动lint-staged 耦合到eslint 和prettier。这样一来,一切都很好地自动化、精简和标准化。
我希望这对某人有所帮助,干杯!