用 inquirer 写交互式的脚本

  最近开发 npm 包,发现基于 inquirer.js 写交互式脚本很方便,尤其是一些部署脚本和打版本号之类的脚步,记录一下。

一、打版本号

  前置依赖:

1
npm i inquirer standard-version -D

  参考 package.json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"name": "release-script",
"version": "0.0.3",
"scripts": {
"release": "node ./scripts/release.js"
},
"devDependencies": {
"cz-conventional-changelog": "^3.3.0",
"inquirer": "^9.2.22",
"standard-version": "^9.5.0"
},
"type": "module",
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
}
}

  对应的 release.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import inquirer from "inquirer";
import { spawn } from "child_process";
// const inquirer = require('inquirer');
// const { spawn } = require('child_process');

const runCommand = (command, args) => {
return new Promise((resolve, reject) => {
const executedCommand = spawn(command, args, {
stdio: "inherit",
shell: true,
});
executedCommand.on("error", (error) => {
reject({ error, message: null, code: null });
});
executedCommand.on("exit", (code) => {
if (code === 0) {
resolve({ error: null, message: null, code });
} else {
reject({ error: null, message: null, code });
}
});
executedCommand.on("message", (message) => {
resolve({ error: null, message: message, code: null });
});
});
};

function execStandardVersion(res) {
const { bumpType, isPrerelease, prereleaseType, tagPrefix } = res;

let cmd = `standard-version --release-as ${bumpType} `;
if (isPrerelease) {
cmd += ` --prerelease ${prereleaseType} `;
}
cmd += ` --tag-prefix ${tagPrefix} `;
cmd += " --infile CHANGELOG.md ";

console.info(`\nExecuting: ${cmd} \n`);

runCommand(cmd)
.then(({ message }) => {
console.info("\nPlease checkout recent commit, and then");
console.info("Push branch and new tag to git repository, publish package to npm");
// message && console.info(message)
})
.catch(({ error, code }) => {
code && console.error("Error: process exit code" + code);
error && console.error(error);
});
}

inquirer
.prompt([
{
type: "list",
name: "bumpType",
message: "Which type you want bump",
choices: ["major", "minor", "patch"],
loop: false,
},
{
type: "confirm",
name: "isPrerelease",
message: "Is a prerelease? Default is no",
default: false,
loop: false,
},
{
type: "list",
name: "prereleaseType",
message: "What is the current stage",
choices: ["alpha", "beta"],
when: (answer) => {
return answer.isPrerelease;
},
loop: false,
},
{
type: "input",
name: "tagPrefix",
message: "Input git tag prefix, default is v",
default: "v",
loop: false,
},
])
.then(execStandardVersion);

二、部署脚步

  待补充

以上

随笔标题:用 inquirer 写交互式的脚本

随笔作者:刘先玉

发布时间:2024年05月29日 - 21:39:46

最后更新:2024年05月29日 - 21:39:46

原文链接:https://liuxianyu.cn/article/inquirer-script.html