Node

node.js CLI 사용성 높이기 - 질문을 통해서 사용자가 옵션 값 선택하게 하기 - 프롬프트 CLI (with inquirer.js)

citron031 2024. 10. 5. 22:22

이전에 node.js 환경에서 CLI 라이브러리를 만드는 작업을 진행했었다.

 

https://citron031.tistory.com/entry/commanderjs%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%9C-js-CLI-%EB%9D%BC%EC%9D%B4%EB%B8%8C%EB%9F%AC%EB%A6%AC-%EA%B5%AC%ED%98%84-with-%EC%98%88%EC%A0%9C

 

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

CLI 라이브러리를 구현하기 위해서는 여러 키워드들에 대해서 알아야 한다. - bin 등록 (package.json의 bin)- 커맨드를 통해 인자를 받기 위한 process.argv- shell 스크립트 작성등등... 위와 같이 CLI 라이

citron031.tistory.com

 

 

그런데, 어떤 라이브러리들은 옵션 없이 단순한 커맨드 라인 명령어만 입력하면, 프로그램 실행 후 사용자에게 질의를 하며 옵션값을 프롬프트로 선택하게끔 하는 기능들이 있었다.

 

몇몇 그런 CLI를 사용하고 보니, 내가 작성했던 커맨드 명령어에 직접 -r 과 같은 옵션을 쓰게 하는 건 사용성 측면에서 아주 별로라고 느껴졌기에 어떻게 하면 다른 좋은 라이브러리들의 방법을 따라할 수 있을까 찾아보게 되었다.

 

그리고, 찾게된 라이브러리는 inquirer 였다 !! 😊

다운로드 수도 아주 많은 보편적인 라이브러리인 inquirer는 아주 많이 사용되고 있어서 안심하고 사용할 수 있겠다 !

싶었지만, 리드미를 읽어보니 지금 이 라이브러리는 유지보수가 잘 안되고, 새로운 대체 라이브러리로 @inquirer/prompts를 사용하라는 것 같았다.

 

https://www.npmjs.com/package/inquirer

 

inquirer

A collection of common interactive command line user interfaces.. Latest version: 11.1.0, last published: 8 days ago. Start using inquirer in your project by running `npm i inquirer`. There are 88943 other projects in the npm registry using inquirer.

www.npmjs.com

요 라이브러리는 유지보수가 잘 안되나보다....

 

https://www.npmjs.com/package/@inquirer/prompts

 

@inquirer/prompts

Inquirer prompts, combined in a single package. Latest version: 6.0.1, last published: 19 days ago. Start using @inquirer/prompts in your project by running `npm i @inquirer/prompts`. There are 1406 other projects in the npm registry using @inquirer/prompt

www.npmjs.com

그래서, 이번에 사용해볼 라이브러리는 이 라이브러리!

기존 라이브러리만큼은 아니지만, 2024-10-05 기준으로 빠르게 다운로드 수가 상승중이며, 언젠가는 inquirer를 대체하지 않을까? 싶다.

 

그래서, 새로이 요 라이브러리와 함께 작성한 최신 CLI 코드는 다음과 같다.

#!/usr/bin/env node

import { Command } from 'commander';
import { input, select, confirm } from '@inquirer/prompts';

program
  .command('get_random')
  .description('Get Random N Colors by inquiry')
  .action(async () => {
    // Step-by-step prompts using individual calls to input/select/confirm
    const number = await input({
      message: 'How many colors do you want to generate? (default is 1)',
      default: '1',
    });

    const format = await select({
      message: 'Which color format do you want?',
      choices: [
        { name: 'HEX', value: 'HEX' },
        { name: 'RGB', value: 'RGB' },
      ],
    });

    const saveToFile = await confirm({
      message: 'Do you want to save the colors to a file?',
      default: false,
    });

    const colors = [];
    const count = parseInt(number, 10);
    for (let i = 0; i < count; i++) {
      let color;
      if (format === 'RGB') {
        const rgb = getRandomColorRgb();
        color = `rgb: ${rgb.red} ${rgb.green} ${rgb.blue}`;
      } else {
        color = getRandomColorHex();
      }
      colors.push(color);
    }

    if (saveToFile) {
      const fileName = generateFileName('random', 'txt');
      writeStringToFile(`./${fileName}`, colors.join('\n'));
      console.log(`Colors saved to ${fileName}`);
    } else {
      console.log(colors.join(' '));
    }
  });

 

이번에 작성한 코드만 따로 가져와서 작성했다.

 

  • 각각의 프롬프트를 input, select, confirm 함수로 개별적으로 호출하는 방식으로 변경하였다.
  • input()은 텍스트 입력을 받고, select()는 옵션을 선택하게 하고, confirm()은 yes/no 형식의 질문을 사용자에게 하여 기존 CLI 옵션 코드를 대체한다.

이렇게 작성한 코드를 빌드 하였는데!

내 rollup 번들러가 에러를 뱉어내었다.

 

 

[!] (plugin commonjs--resolver) RollupError: node_modules/iconv-lite/encodings/tables/gb18030-ranges.json (1:9): Expected ';', '}' or <eof> (Note that you need @rollup/plugin-json to import JSON files)

 

붉은색으로 쓰여 있어서 에러는 빠르게 찾았다.

해당 에러에 대해서 알아보니,  (사실 친절하게 작성되어 있기도 하지만)

@rollup/plugin-json 플러그인을 설정하라는 의미였다.

빌드 과정에서 JSON 파일이 새로 생겼는데, 번들러에 JSON을 다루는 기능이 연결되어있지 않았나보다.

 

npm install @rollup/plugin-json --save-dev

 

해당 플러그인을 설치하고 rollup.config.js에 설정해주자.

import { defineConfig } from 'rollup';
import json from '@rollup/plugin-json';

export default defineConfig({
  input: {...},
  output: [...],
  plugins: [
    json(),
    ...
  ],
});

 

이제 다시 빌드를 하면! 성공한다 👍

 

이제 라이브러리를 배포해보고, 직접 CLI 기능을 테스트해보면!

 

 

잘 작동하는 것을 확인해볼 수 있다!

 

참고로 비교해보자면, 이전에는 아래와 같이 커맨드 라인 명령어에 필요한 옵션들을 직접 넣어줘야 했다...

npx cht random 5 -r

 

 

실제 작성한 코드의 커밋은 아래 링크에서 확인해볼 수 있다 !!! 🙌

https://github.com/citron03/colors-helper-tools/commit/29249e5f807828deafe830920115da3f583321f5

 

upgrade cli function with inquirer · citron03/colors-helper-tools@29249e5

citron03 committed Oct 5, 2024

github.com