命令行工具:CLI 是在命令行終端使用的工具,如git, npm, vim 都是CLI工具。比如我們可以通過 git clone 等命令簡單把遠程代碼復制到本地
和 cli 相對的是圖形用戶界面(gui),gui 側重於易用,cli 則側重於效率。
如何開發一個CLI工具?
先初始化一個項目:
mkdir plgcli
cd plgcli
創建 plgcli文件夾, 進入文件夾
修改 package.json文件,增加bin字段
{
"name": "plgcli",
"version": "1.0.0",
"description": "PLG CLI tool",
"main": "index.js",
"bin": {
"PLG": "./bin/index.js"
},
"scripts": {
"test": "test"
},
"keywords": [
"PLG",
"CLI",
"Tool"
],
"author": "winyh",
"license": "ISC",
"dependencies": {
"commander": "^2.20.0"
}
}
運行 node index.js
#!/usr/bin/env node console.log('hello ')
一般 cli都有一個特定的命令,比如 git,剛才使用的 code 等,我們也需要設置一個命令,就叫 PLG 吧!如何讓終端識別這個命令呢?很簡單,打開 package.json 文件,添加一個字段 bin,並且聲明一個命令關鍵字和對應執行的文件:如上
然后我們測試一下,在終端中輸入 PLG,會提示:
command not found: PLG
為什么會這樣呢?回想一下,通常我們在使用一個 cli 工具時,都需要先安裝它
而我們的 PLG-cli 並沒有發布到 npm 上,當然也沒有安裝過了,所以終端現在還不認識這個命令。通常我們想本地測試一個 npm 包,可以使用:npm link 這個命令,本地安裝這個包,我們執行一下
然后再執行
PLG
命令,看正確輸出 hello world! 了
1.完成查看版本的功能
如PLG -v
有兩個問題
1.如何獲取參數?
2.如何獲取版本信息?
在 node 程序中,通過 process.argv 可獲取到命令的參數,以數組返回
2.執行復雜命令
有點多個參數時,或者或者像新建項目這種需要用戶輸入項目名稱(我們稱作“問答”)的命令時,通過 switch case 和 process.argv 獲取參數就力不從心了,這時需要引入專門處理命令行交互的包commander.提供了用戶命令行輸入和參數解析強大功能
commander已經為我們創建好了幫助信息,以及兩個參數 -V 和 -h
3.添加問答操作
引入inquirer包文件,修改 index.js文件
#!/usr/bin/env node const program = require('commander'); const inquirer = require("inquirer"); const initAction = () => { inquirer.prompt([{ type:"input", message:"請輸入項目名稱:", name:'name' }]).then( answers => { console.log(`項目名為: ${answers.name}`) }) } program.version(require("../package.json").version) program .command("init") .description("創建項目") .action(initAction) program.parse(process.argv)
4.運行shell腳本
引入shelljs庫
5.cli 工具發布到 npm
npm publish