How to Develop CLI Tools with Claude Code
Learn how to develop cli tools using Claude Code. Includes practical code examples and step-by-step guidance.
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を参照してください。
Summary
Claude Codeを使えば、引数パース、対話型入力、プログレス表示、テストまで含めたCLIツールを短時間で開発できます。「こんなコマンドが欲しい」と自然言語で伝えるだけで、すぐに動くツールが完成します。
詳しくはClaude Code公式ドキュメントを参照してください。
Related Posts
How to Supercharge Your Side Projects with Claude Code [With Examples]
How to Supercharge Your Side Projects with Claude Code [With Examples]. A practical guide with code examples.
How to Automate Refactoring with Claude Code
Learn how to automate refactoring using Claude Code. Includes practical code examples and step-by-step guidance.
Complete CORS Configuration Guide with Claude Code
Learn about complete cors configuration guide using Claude Code. Practical tips and code examples included.