yargs API的使用
标题 | |
---|
usage | 用法说明 |
alias | 重命名 |
wrap | 设置整块命令区域的高度 |
demandCommand | 期望最少输入xx个命令 |
epilogue | 页脚内容 |
recommendCommands | 输入错误时,会有近似命令提示 |
strict | 不能识别时,会有错误提示 |
fail | 错误信息,可以自定义 |
command | 封装命令 |
option | 设置单个全局选项 |
options | 设置一组全局选项 |
group | 设置一组全局选项的key |
parse | 解析参数 |
yargs的实践
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers');
const cli = yargs(hideBin(process.argv));
cli.usage('Usage: $0 <command> [options]')
.alias('v', 'version').alias('h', 'help')
.wrap(100)
.demandCommand(1, "期望最少输入1个命令")
.epilogue('底部显示的文案')
.recommendCommands()
.strict()
.fail((err, msg) => {
console.log(err)
console.error(msg)
})
.command('test', '这是一条测试的命令',
(yargs) => {
yargs.positional('name', {
describe: '默认name值',
default: 'defaultName'
})
return yargs;
},
(argv) => {
console.log(argv)
}
)
.command({
command: 'test2 [name]',
aliases: ['t2','tst2'],
describe: '这是另外一条测试的命令',
builder: (yargs) => {
},
handler: (argv) => {
console.log(argv)
}
})
.option('options1', {
type: 'string',
describe: '这是全局options1',
alias: 'opt1'
})
.options({
options2: {
type: 'boolean',
describe: '这是全局options2',
alias: 'opt2'
},
options3: {
type: 'number',
describe: '这是全局options3',
alias: 'opt3'
},
options4: {
type: 'number',
describe: 'options4被隐藏了',
alias: 'opt4',
hidden: true,
}
})
.group(
['options1', 'options2', 'options3','options4'],
'全局选项:'
)
.parse();
预览
Usage: xxx <command> [options]
命令:
xxx command 这是一条测试的命令
xxx command2 [name] 这是另外一条测试的命令 [aliases: t2, tst2]
全局选项:
--options1, --opt1 这是全局options1 [字符串]
--options2, --opt2 这是全局options2 [布尔]
--options3, --opt3 这是全局options3 [数字]
选项:
-v, --version 显示版本号 [布尔]
-h, --help 显示帮助信息 [布尔]
底部显示的文案