icore Node.js
在此页面上

icore

TypeScript 7 icore 3.0.2

用于在 Node.js 中构建结构清晰的命令行界面的模块。灵感源自整洁架构(Clean Architecture)理念。

安装

Shell
npm install icore

第一条命令

定义带有 --name 和 --uppercase 选项的 hello 命令。将各条命令收集到注册表中,然后传给 createTerminalApp()。在 handle 函数中,options.name 的类型是 string,options.uppercase 的类型是 boolean。

cli.ts
import { createCommand, createTerminalApp } from 'icore';

const command = createCommand();

const commands = command.registry([
  command.define({
    path: ['hello'],
    options: {
      name: {
        type: 'string',
        default: 'world'
      },
      uppercase: {
        type: 'boolean',
        default: false
      }
    },
    handle({ options }) {
      const greeting = `Hello, ${options.name}!`;

      return `${options.uppercase ? greeting.toUpperCase() : greeting}\n`;
    }
  })
] as const);

const app = createTerminalApp({ commands });

async function main(args: readonly string[]): Promise<void> {
  process.exitCode = await app.run(args, undefined, {
    strict: true
  });
}

void main(process.argv.slice(2));

将 cli.ts 编译为 dist/cli.js 后,执行以下命令会输出 HELLO, ALICE!。

Shell
node dist/cli.js hello --name Alice --uppercase

app.run(...) 验证参数、执行处理函数并写入结果。在 strict: true 模式下,命令名和子命令必须放在选项之前。