はじめに
NodejsでCLIツールを作成するときに良さそうなパッケージを見つけて、実際に使ってみたら良かったので紹介していきます。
使ったパッケージ
cac
シンプルでパワフルなコマンドラインインターフェイスを作るためのフレームワーク
https://www.npmjs.com/package/cac
inquirer.js
対話型のインターフェースを組み込むのに便利
https://www.npmjs.com/package/inquirer
インストール
$npm i cac inquirer
$npm i --save-dev @types/inquirer
サンプル
cacを使ってCLIの骨組みを書いていきます。
下記の例では cli hello hogeみたいなコマンドを入力されたときに処理が実行されるようにしています。
cli.ts
importindexfrom'../src/index'importcacfrom'cac'constcli=cac()cli.command('hello [name]','Enter your name').action(()=>{index()})cli.help()cli.parse()inquirerを使って対話型のインタフェースを定義していきます。
下記の例では、入力とリストとチェックボックスの対話型インターフェースを定義しています。
index.ts
import{prompt,Separator,QuestionCollection}from'inquirer'exportdefaultasync():Promise<void>=>{constname=process.argv[3]if(!name){console.error('Please pass one argument!!')process.exit(1)}constmsg=`
Hello!! ${name} !!!
`console.log(msg)// InputconstinputQuestions:QuestionCollection=[{type:'input',message:"What's your name",name:'name'}]awaitprompt(inputQuestions).then((answers:any)=>{console.log(JSON.stringify(answers,null,''))})// ListconstlistQuestions:QuestionCollection=[{type:'list',name:'color',message:'What do you like color?',choices:['black','red',{name:'orange',disabled:'disabled'},'green']}]awaitprompt(listQuestions).then((answers:any)=>{console.log(JSON.stringify(answers,null,''))})// CheckboxconstcheckboxQuestions:QuestionCollection=[{type:'checkbox',message:'select',name:'select',choices:[newSeparator(' = Choise A = '),{name:'hoge'},{name:'fuga'},{name:'foo'}],validate:(answer:any):boolean|string=>{if(answer.length<1){return'You must choose'}returntrue}}]awaitprompt(checkboxQuestions).then((answers:any)=>{console.log(JSON.stringify(answers,null,''))})}実行する
ビルドするのが面倒なので ts-nodeで実行してきます。
$npx ts-node bin/cli.ts hello test
Hello!! test !!!
? What's your name is_ryo
{
"name": "is_ryo"
}
? What do you like color? red
{
"color": "red"
}
? select hoge, fuga, foo
{
"select": [
"hoge",
"fuga",
"foo"
]
}
さいごに
サクッと対話型のCLIを作ることができました。
これでCLIを作るときの雛形はできるので、自作CLIを作っていきましょう!
ではまた!!!