LoginSignup
5
3

More than 3 years have passed since last update.

Nodejs(TypeScript)とcacとinquirer.jsでサクッとCLIを作成する

Posted at

はじめに

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
import index from '../src/index'
import cac from 'cac'

const cli = cac()

cli.command('hello [name]', 'Enter your name').action(() => {
  index()
})

cli.help()
cli.parse()

inquirer を使って対話型のインタフェースを定義していきます。
下記の例では、入力とリストとチェックボックスの対話型インターフェースを定義しています。

index.ts
import { prompt, Separator, QuestionCollection } from 'inquirer'

export default async (): Promise<void> => {
  const name = process.argv[3]

  if (!name) {
    console.error('Please pass one argument!!')
    process.exit(1)
  }

  const msg = `
    Hello!! ${name} !!!
  `
  console.log(msg)

  // Input
  const inputQuestions: QuestionCollection = [
    {
      type: 'input',
      message: "What's your name",
      name: 'name'
    }
  ]
  await prompt(inputQuestions).then((answers: any) => {
    console.log(JSON.stringify(answers, null, '  '))
  })

  // List
  const listQuestions: QuestionCollection = [
    {
      type: 'list',
      name: 'color',
      message: 'What do you like color?',
      choices: [
        'black',
        'red',
        {
          name: 'orange',
          disabled: 'disabled'
        },
        'green'
      ]
    }
  ]
  await prompt(listQuestions).then((answers: any) => {
    console.log(JSON.stringify(answers, null, '  '))
  })

  // Checkbox
  const checkboxQuestions: QuestionCollection = [
    {
      type: 'checkbox',
      message: 'select',
      name: 'select',
      choices: [
        new Separator(' = Choise A = '),
        { name: 'hoge' },
        { name: 'fuga' },
        { name: 'foo' }
      ],
      validate: (answer: any): boolean | string => {
        if (answer.length < 1) {
          return 'You must choose'
        }

        return true
      }
    }
  ]
  await prompt(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を作っていきましょう!
ではまた!!!

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3