← 中文资源

简体中文版本

Commander.js CLI 工具模板

使用 Commander.js、TypeScript、chalk 彩色输出和 inquirer 交互提示的 CLI 项目模板。

阅读英文原文

模板说明

该模板提供带子命令、类型化选项和交互提示的 Node.js CLI 基础,适合开发者和运维工具。

包含内容

包含 Commander 命令树、TypeScript 配置、chalk 终端样式、inquirer 交互提示、构建脚本和测试入口。bin 入口与业务逻辑分离,便于测试。

使用建议

保持 stdout 机器可读,诊断信息写入 stderr;用法错误与运行时失败使用不同退出码。非 TTY 环境禁用交互提示并提供参数回退。发布前用 npm pack --dry-run 检查内容。

验证方式

以子进程运行构建后的 CLI,断言帮助文本、选项解析、退出码和错误输出;测试非交互模式与非法参数。

交付检查

使用该模板初始化项目后,先运行安装、类型检查、测试与生产构建;再按模板说明逐项核对环境变量、权限边界、错误处理和关闭流程。把实际命令输出保留为交付证据,不要只依据 README 声明。

代码示例

package.json
src/index.ts
src/commands/init.ts
src/commands/build.ts
src/builder.ts
{
  "name": "my-cli-tool",
  "version": "1.0.0",
  "type": "module",
  "bin": {
    "mycli": "./dist/index.js"
  },
  "scripts": {
    "dev": "tsx src/index.ts",
    "build": "tsc",
    "start": "node dist/index.js"
  },
  "dependencies": {
    "commander": "^12.1.0",
    "chalk": "^5.3.0",
    "inquirer": "^12.0.0"
  },
  "devDependencies": {
    "typescript": "^5.6.0",
    "tsx": "^4.19.0"
  }
}
#!/usr/bin/env node
import { Command } from 'commander';
import { initCommand } from './commands/init';
import { buildCommand } from './commands/build';

const program = new Command();

program
  .name('mycli')
  .description('A CLI tool built with Commander.js')
  .version('1.0.0');

program.addCommand(initCommand);
program.addCommand(buildCommand);

program.parse();
import { Command } from 'commander';
import chalk from 'chalk';
import inquirer from 'inquirer';

export const initCommand = new Command('init')
  .description('Initialize a new project')
  .option('-n, --name <name>', 'project name')
  .action(async (options) => {
    const answers = await inquirer.prompt([
      {
        type: 'input',
        name: 'projectName',
        message: 'Project name:',
        default: options.name || 'my-project',
      },
      {
        type: 'list',
        name: 'template',
        message: 'Choose a template:',
        choices: ['basic', 'advanced', 'minimal'],
      },
    ]);

    console.log(chalk.green(`Initializing ${answers.projectName}...`));
    console.log(chalk.blue(`Template: ${answers.template}`));
  });
import { Command } from 'commander';
import chalk from 'chalk';
import { buildProject } from '../builder';

export const buildCommand = new Command('build')
  .description('Build the project')
  .option('-w, --watch', 'watch for changes')
  .option('-o, --output <dir>', 'output directory', 'dist')
  .action(async (options) => {
    console.log(chalk.cyan('Building project...'));
    console.log(chalk.gray(`Output: ${options.output}`));

    try {
      await buildProject(options);
      console.log(chalk.green('Build complete!'));
    } catch (err) {
      console.error(chalk.red('Build failed:'), err);
      process.exit(1);
    }
  });
import { readdirSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
import { join, extname } from 'path';

export async function buildProject(options: { watch: boolean; output: string }) {
  mkdirSync(options.output, { recursive: true });

  const files = readdirSync('src');
  for (const file of files) {
    if (extname(file) === '.ts') {
      const content = readFileSync(join('src', file), 'utf-8');
      const outName = file.replace(/\.ts$/, '.js');
      writeFileSync(join(options.output, outName), content);
    }
  }
}