如何Develop CLI Tools:Claude Code 实战指南
学习如何develop cli tools:Claude Code 实战. 包含实用代码示例和分步指导。
CLIツール开发を通过 Claude Code 加速
自分専用のCLIツールを作りたいとき、Claude Code 最高のパートナーです。参数のパース、サブコマンド设计、インタラクティブな入输出まで、「こんなCLIを作りたい」と伝える只需实现可以。
项目の初期结构
> TypeScriptでCLIツールの项目を作って。
> commanderで参数をパースして、eslintとprettierも配置して。
> npx ts-node src/index.ts で実行できるようにして。
参数パースとサブコマンド
Commander使用…的CLIの基本構造です。
#!/usr/bin/env node
import { Command } from "commander";
import { version } from "../package.json";
const program = new Command();
program
.name("mytool")
.description("プロジェクト管理CLIツール")
.version(version);
program
.command("init")
.description("プロジェクトを初期化する")
.option("-t, --template <name>", "テンプレート名", "default")
.option("-d, --dir <path>", "作成先ディレクトリ", ".")
.action(async (options) => {
console.log(`テンプレート「${options.template}」で初期化中...`);
await initProject(options.template, options.dir);
console.log("完了しました!");
});
program
.command("generate <type> <name>")
.alias("g")
.description("ファイルを生成する(component, hook, page)")
.option("--dry-run", "実際にファイルを作成せずプレビュー")
.action(async (type, name, options) => {
if (options.dryRun) {
console.log(`[dry-run] ${type}「${name}」を生成します`);
return;
}
await generateFile(type, name);
});
program
.command("check")
.description("プロジェクトの状態を確認する")
.action(async () => {
await runHealthCheck();
});
program.parse();
インタラクティブな输入
Inquirer库使用…的対話类型输入の实现です。
import inquirer from "inquirer";
import chalk from "chalk";
interface ProjectConfig {
name: string;
framework: string;
features: string[];
packageManager: string;
}
async function interactiveInit(): Promise<ProjectConfig> {
const answers = await inquirer.prompt([
{
type: "input",
name: "name",
message: "プロジェクト名:",
validate: (input: string) =>
/^[a-z0-9-]+$/.test(input) || "小文字英数字とハイフンのみ使用できます",
},
{
type: "list",
name: "framework",
message: "フレームワーク:",
choices: ["React", "Next.js", "Astro", "Vue"],
},
{
type: "checkbox",
name: "features",
message: "追加機能:",
choices: [
{ name: "TypeScript", checked: true },
{ name: "ESLint", checked: true },
{ name: "Prettier", checked: true },
{ name: "Testing (Vitest)" },
{ name: "CI/CD (GitHub Actions)" },
],
},
{
type: "list",
name: "packageManager",
message: "パッケージマネージャー:",
choices: ["npm", "pnpm", "yarn"],
},
]);
console.log(chalk.green("\n設定内容:"));
console.log(chalk.cyan(` プロジェクト名: ${answers.name}`));
console.log(chalk.cyan(` フレームワーク: ${answers.framework}`));
console.log(chalk.cyan(` 機能: ${answers.features.join(", ")}`));
return answers;
}
プ日志レスバーとスピナー
処理の進捗を視覚的に显示します。
import ora from "ora";
import cliProgress from "cli-progress";
async function processFiles(files: string[]) {
const bar = new cliProgress.SingleBar({
format: "処理中 |{bar}| {percentage}% | {value}/{total} ファイル",
barCompleteChar: "█",
barIncompleteChar: "░",
});
bar.start(files.length, 0);
for (const file of files) {
await processFile(file);
bar.increment();
}
bar.stop();
console.log(chalk.green("すべてのファイルの処理が完了しました!"));
}
async function installDependencies(packages: string[]) {
const spinner = ora("依存パッケージをインストール中...").start();
try {
await execAsync(`npm install ${packages.join(" ")}`);
spinner.succeed("依存パッケージのインストール完了");
} catch (error) {
spinner.fail("インストールに失敗しました");
throw error;
}
}
测试の实现
CLIツールの测试も让 Claude Code依頼可以。
import { describe, it, expect } from "vitest";
import { execSync } from "child_process";
describe("mytool CLI", () => {
it("バージョンを表示できる", () => {
const output = execSync("npx ts-node src/index.ts --version").toString();
expect(output.trim()).toMatch(/^\d+\.\d+\.\d+$/);
});
it("ヘルプを表示できる", () => {
const output = execSync("npx ts-node src/index.ts --help").toString();
expect(output).toContain("プロジェクト管理CLIツール");
expect(output).toContain("init");
expect(output).toContain("generate");
});
it("存在しないコマンドでエラーになる", () => {
expect(() => {
execSync("npx ts-node src/index.ts unknown 2>&1");
}).toThrow();
});
});
npm包作为公開する方法はnpm包公開。Claude Codeの基本的使い方は入門指南を、生産性向上のコツは生産性を3倍にする10のTips。
总结
借助 Claude Code,参数パース、対話类型输入、プ日志レス显示、测试まで含めたCLIツールを短时间で开发可以。「こんなコマンドが欲しい」と自然言語で伝える只需、すぐに動くツールが完成します。
详情请参阅Claude Code官方文档。
#Claude Code
#CLI
#Node.js
#Commander
#development tools
Related Posts
Use Cases
Use Cases
用 Claude Code 加速个人项目开发【附实战案例】
详解如何用 Claude Code 大幅提升个人项目的开发速度。包含从创意到上线的完整实战案例和工作流。
Use Cases
Use Cases
如何用 Claude Code 自动化代码重构
详解如何利用 Claude Code 高效完成代码重构自动化。包含实用提示词和真实项目中的重构模式。
Use Cases
Use Cases
Complete CORS Configuration Guide:Claude Code 实战指南
了解complete cors configuration guide:Claude Code 实战. 包含实用技巧和代码示例。