commander) CLI 명령어 만들기

김명성·2022년 7월 25일
0
  1. index 파일에. commander를 import 해오고, argv를 파싱한다.
import { program } from "commander";
import { serveCommend } from "./src/serve";

program.addCommand(serveCommend)


program.parse(process.argv);

  1. serve.ts에서 commend instance를 작성한다.
import { Command } from "commander";

export const serveCommend = new Command().command('serve').description('Open a file for editing')
.action(() => {
  console.log('Getting ready to serve a file')
})

  1. command 메서드로 실행될 명령어를 작성하고, description으로 명령에 대한 추가설명을, action으로 어떤 행동이 실행되어야 하는지 작성한다.

  1. option method를 통해 command chainning을 구현할 수 있다.
export const serveCommend = new Command()
.command('serve [filename]')
.description('Open a file for editing')
.option('-p, --port <number>', 'port to run server on','4005')
.action((filename = 'notebook.js', options) => {
  console.log(filename,options)
})

대괄호 안에 입력된 값은 optional을 의미하고 꺽쇠 안에 입력된 값은 require를 의미한다.
option 메서드의 인수는 commend에 이을 명렁어 chainning(flag), chaining command에 대한 description, defaultvalue 순으로 작성한다.

0개의 댓글