JavaScript

commander.js를 사용한 js CLI 라이브러리 구현 (with 예제)

citron031 2024. 6. 4. 21:56

CLI 라이브러리를 구현하기 위해서는 여러 키워드들에 대해서 알아야 한다.

 

- bin 등록 (package.json의 bin)

- 커맨드를 통해 인자를 받기 위한 process.argv

- shell 스크립트 작성

등등...

 

위와 같이 CLI 라이브러리 구현을 위해서 많은 고려사항들이 있다.

 

이때, commander.js을 사용하면 js로 간단하게 나만의 cli 라이브러리를 구현할 수 있다.

 

commander.js는 Node.js 환경에서 CLI를 쉽게 작성할 수 있게 해주는 라이브러리로, 명령어와 옵션을 간단하게 정의하고 파싱할 수 있는 기능을 제공한다.

🎶 복잡한 코드 작성과 테스트 과정을 줄일 수 있다.

 

npm i commander

 

commander를 설치한 뒤, 다음의 예제 코드를 살펴보자.

 

❓ #!/usr/bin/env node

Unix 계열 운영 체제에서 스크립트 파일이 어떤 인터프리터에 의해 실행될지를 지정하는 "shebang"이다.

이 스크립트가 Node.js 인터프리터를 사용하여 실행되어야 함을 나타낸다.

#!/usr/bin/env node

import { Command } from 'commander';
import { getRandomColorHex, getRandomColorRgb } from '..';

const program = new Command();
const version = '1.5.9';

program
  .name('colors-helper-tools')
  .description('colors-helper-tools helps you control colors !')
  .version(`colors-helper-tools version 🎶 ${version}`);

program
  .command('random')
  .description('Get Random N Colors (default HEX)')
  .argument('[number]', 'number you want to get (default 1)', '1')
  .option('-r, --rgb', 'get rgb colors')
  .action((number, options) => {
    const isRgb = !!options.rgb;
    const colors = [];
    for (let i = 0; i < Number(number); i++) {
      let color = '';
      if (isRgb) {
        const rgb = getRandomColorRgb();
        color += `rgb: ${rgb.red} ${rgb.green} ${rgb.blue}`;
      } else {
        color = getRandomColorHex();
      }
      colors.push(color);
    }
    console.log(colors.join(' '));
  });

program.parse();

위 코드는 commander.js를 사용해 랜덤으로 색상을 출력하는 cli 라이브러리의 코드이다.

 

argument를 통해서 랜덤으로 출력할 색상의 개수를 정한다.

만약, argument 값을 작성하지 않았으면 default value로 설정한 1, 즉 하나의 색상값만 출력하게 된다.

 

option은 미리 설정한 옵션을 바탕으로 사용자에게 여러 기능을 제공한다.

위의 라이브러리는 -r 혹은 --rgb 옵션이 있는데, 해당 옵션을 사용하면 hex값이 아닌 rgb 0 ~ 256 값을 출력하도록 설정되어 있다.

 

그리고 .action에서 실제로 해당 라이브러리가 어떻게 작동하는지 설정할 수 있다.

위에서 설정한 argument(위의 예제에서는 number), options 값을 바탕으로 실제 어떤 기능으로 CLI가 작동하게 할지 설정한다.

 

Commander.js는 js 혹은 ts로 작성되기 때문에 node, ts-node를 사용해 실제 해당 CLI 명령어를 미리 테스트해볼 수 있다.

npx ts-node ./src/cli.ts

or

node ./src/cli.js

 

그리고 실제 배포된 뒤, 해당 패키지를 install한 사용자가 npx로 해당 CLI 명령어를 사용할 수 있도록 package.json bin에 등록해준다.

 

🍎 설치한 CLI 라이브러리의 스크립트는 node_modules/.bin에 위치하게 된다.

해당 위치에 존재하는 스크립트만 npx 명령어로 실행할 수 있다.

{
  "name": "colors-helper-tools",
  "version": "1.5.9",
  "description": "help use color style ✨",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "bin": {
    "cht": "dist/src/cli.js"
  },
  "scripts": {
    "build": "tsc",
    "test": "jest"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/citron03/colors-helper-tools.git"
  },
  "keywords": [
    "color",
    "css",
    "hex",
    "random"
  ],
  "author": "citron03",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/citron03/colors-helper-tools/issues"
  },
  "homepage": "https://github.com/citron03/colors-helper-tools#readme",
  "devDependencies": {
    "@babel/cli": "^7.22.9",
    "@babel/core": "^7.22.9",
    "@babel/preset-env": "^7.22.9",
    "@babel/preset-typescript": "^7.22.5",
    "@types/jest": "^29.5.3",
    "jest": "^29.6.2",
    "ts-node": "^10.9.1",
    "typescript": "^5.0.4"
  },
  "engines": {
    "node": ">=14"
  },
  "dependencies": {
    "commander": "^12.1.0"
  }
}

위와 같이 package.json의 bin에 cht로 설정한 경우, 해당 라이브러리를 설치한 뒤 다음과 같은 명령어로 구현한 CLI 기능을 사용할 수 있다.

npx cht random 5 -r

위의 기능은 랜덤 5개의 색상을 rgb 값 형태로 콘솔창에 출력한다.

 

👍참고 자료 

https://www.npmjs.com/package/colors-helper-tools

 

colors-helper-tools

help use color style ✨. Latest version: 1.5.9, last published: 5 minutes ago. Start using colors-helper-tools in your project by running `npm i colors-helper-tools`. There are no other projects in the npm registry using colors-helper-tools.

www.npmjs.com

https://www.npmjs.com/package/commander#command-arguments

 

commander

the complete solution for node.js command-line programs. Latest version: 12.1.0, last published: 17 days ago. Start using commander in your project by running `npm i commander`. There are 82387 other projects in the npm registry using commander.

www.npmjs.com

 

 

😊 잘못된 내용이 있다면, 댓글로 알려주세요 !