1. 先来一个hello world
在package.json中添加
{
"bin": {
"hellocli": "./index.js"
}
}
作用是申明命令叫做hellocli,入口文件是index.js。
我们想用类似vue create hello-world这种全局命令,怎么办呢?
使用npm install . -g 或者npm link来把命令注册为全局命令。
在index.js中写入
#!/usr/bin/env node
console.log('hello myCLI')
注意一定要写#!/usr/bin/env node不然不生效。现在我们测试下命令,在终端运行hellocli
2. 使用命令行交互
2.1 首先安装npm i commander -S
commander: 完整的 node.js 命令行解决方案。更多可以参考文档
在index.js中添加
/**
* 捕获命令行输入的参数
*/
program
.command("create <name>")
.action((res)=>{
console.log(res)
})
program.parse(process.argv);
解释:
command是申明一个命令,即你可以使用hellocli create这种命令;
<name>是用户输入的名称变量;
program.parse(process.argv)是用来解析命令行输入的参数;
action可以获取到<name>,这里把<name>输出
2.2 安装 npm i inquirer -S
inquirer: 通用的命令行用户界面集合,用于和用户进行交互。更多参考文档
在index.js里面添加
const inquirer = require('inquirer');
let list = [
{
type: 'list',
name: 'single',
message: '选择其中一个',
choices: [
'苹果',
'香蕉',
'橘子',
]
},
{
type: 'checkbox',
message: '多选',
name: 'multiple',
choices: [
{
name: '跑步',
},
{
name: '举哑铃',
},
{
name:"俯卧撑"
}]
}
]
program
.command("create <name>")
.action(async(res)=>{
let listRes = await inquirer.prompt(list);
console.log(listRes)
console.log(res)
})
说明:
type可选值有input, number, confirm, list, rawlist, expand, checkbox, password, editorname这里定义的,会在结果中体现如下图message是提示语choices是选项列表的数组- 更多可以参考文档
效果图如下:
最终打印结果
至此,我们可以通过commander获取到用户输出的参数,可以通过inquirer获取到用户选择的选项。其他的可以根据node的一些语法对这些获取的参数进行处理。
可以参考下我写的CLI
- 本文链接:https://harry-qi.github.io/2021/02/10/%E5%BC%80%E5%8F%91CLI/
- 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。