如何使用commander及一些常见库来开发一个 自定义CLI(Command Line Interface)

以TypeScript 项目为例:

首先,确保你的项目已经初始化,并且已经安装了 TypeScript。创建一个新的文件夹,并进入该文件夹。

mkdir my-cli
cd my-cli

接下来,初始化你的项目:

npm init -y

安装一些常见的依赖:

npm install chalk clear commander figlet glob inquirer ora yaml

创建一个 src 文件夹,并在其中创建一个名为 index.ts 的文件。这将是你的 CLI 入口文件。

mkdir src
touch src/index.ts

打开 index.ts 文件,并添加以下代码:

#!/usr/bin/env node

import * as chalk from 'chalk';
import * as clear from 'clear';
import * as figlet from 'figlet';
import * as glob from 'glob';
import * as inquirer from 'inquirer';
import * as ora from 'ora';
import * as yaml from 'js-yaml';
import { Command } from 'commander';

clear();

console.log(chalk.yellow(figlet.textSync('My CLI', { horizontalLayout: 'full' })));

const program = new Command();

program.version('1.0.0').description('My CLI');

program
  .command('hello')
  .alias('h')
  .description('Say hello')
  .action(() => {
    console.log(chalk.green('Hello!'));
  });

program
  .command('list <pattern>')
  .alias('l')
  .description('List files')
  .action((pattern: string) => {
    glob(pattern, (err: Error | null, files: string[]) => {
      if (err) {
        console.error(chalk.red('An error occurred while listing files:', err));
        return;
      }

      console.log(chalk.blue('Files matching the pattern:'));
      files.forEach((file) => {
        console.log(file);
      });
    });
  });

program
  .command('config')
  .alias('c')
  .description('Display configuration')
  .action(() => {
    const config = yaml.safeLoad(`
      name: My CLI
      version: 1.0.0
      author: John Doe
      ...
    `);
    console.log(chalk.yellow('Configuration:'));
    console.log(config);
  });

program.parse(process.argv);

以上代码示例了一个简单的 CLI,使用了 chalk 来添加彩色输出,clear 来清除控制台,figlet 来创建 CLI 的 ASCII 标题,glob 来查找文件,inquirer 来获取用户输入,ora 来显示加载状态,yaml 来解析 YAML 配置文件,并使用 commander 来定义和解析命令。

注意:这个示例假设你已经正确安装了上述依赖,并且在 TypeScript 项目中配置了相关的类型声明。

现在,在 package.json 文件中添加一个 bin 字段,指向入口文件:

{
  "name": "my-cli",
  "version":

 "1.0.0",
  "description": "My CLI",
  "bin": {
    "my-cli": "./dist/index.js"
  },
  ...
}

最后,构建你的 TypeScript 代码并运行 CLI:

npx tsc
./dist/index.js

现在你可以在命令行中运行 my-cli hello 来触发相应的操作,也可以尝试其他命令,如 my-cli list "*.txt"my-cli config

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值