使用 commander && inquirer 构建专业的node cli
备注:
比较简单就是使用nodejs 的两个类库帮助我们进行开发而已,具体的使用参考类库文档
1. 项目初始化
a. 安装依赖
yarn init -y
yarn add commander inquirer
├── README.md
├── bin
│ └── index.js
├── package.json
└── yarn.lock
2. 项目代码
a. package.json
{
"name": "mynode-cli",
"version": "1.0.2",
"main": "bin/index.js",
"license": "MIT",
"dependencies": {
"commander": "^2.12.2",
"inquirer": "^4.0.2"
},
"bin": {
"mynode-cli":"bin/index.js"
},
"scripts": {
"publish":"npm publish",
"run-local":"node bin/index"
}
}
b. bin/index.js
备注:主要操作
#!/usr/bin/env node
const Program = require("commander");
const Prompt = require("inquirer");
const initQuestions = [{
type: 'list',
name: 'plattype',
message: '请选择平台类型?',
choices: [
'pass',
'sass',
'iaas'
]
},
{
type: 'list',
name: 'vmCounts',
message: '请选择您包含的虚拟机数量?',
choices: ['100', '200', '500', '1000']
}
];
const loginQuestions = [{
type: 'input',
name: 'username',
message: '请输入用户名',
},
{
type: 'password',
name: 'password',
message: '请输入用户密码'
}
];
Program
.version("0.1.0")
.description("系统平台初始化工具")
.option("-i, --init","平台初始化")
Program
.command("init")
.alias("i")
.description("初始化平台")
.action(() => {
Prompt.prompt(initQuestions).then(result => {
console.log("您选择的平台类型信息如下:");
console.log(JSON.stringify(result));
})
});
Program
.command("login")
.alias("l")
.description("登陆平台")
.action(() => {
Prompt.prompt(loginQuestions).then(result => {
console.log("您登陆的账户信息如下:");
console.log(JSON.stringify(result));
})
})
Program.parse(process.argv);
3. 使用
a. 安装
npm install -g mynode-cli
b. 使用
mynode-cli -i init
mynode-cli -i login
mynode-cli -h
参考界面如下:
![](https://images2017.cnblogs.com/blog/562987/201801/562987-20180109091943910-630431003.png)
![](https://images2017.cnblogs.com/blog/562987/201801/562987-20180109091944285-1263921642.png)
![](https://images2017.cnblogs.com/blog/562987/201801/562987-20180109091944535-1777464093.png)
4. 总结
还是比较简单的,同时有一个npm 包create-new-cli也是一个不错的选择
5.参考资料
https://www.npmjs.com/package/commander
https://www.npmjs.com/package/inquirer
https://github.com/rongfengliang/mynode-cli