How to 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 활용. 실용적인 팁과 코드 예시를 포함합니다.