0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Commander.jsでサブコマンドの下にさらにコマンドを作れると知るまで

0
Last updated at Posted at 2026-03-22

TypeScript の学習として、TypeScript と Commander.js で tino という小さなツールを作り始めました。

最初に作ろうとしたのは、Task を追加する次のようなコマンドです。

tino task add <title>

1. 失敗

最初は add を文字列で判定しようとして、以下のようなコードを書きました。

import { Command } from "commander";

const program = new Command();

program
  .command("task")
  .argument("<cmd>")
  .argument("<title>")
  .action((cmd, title) => {
    if (cmd === "add") {
      console.log(`Adding ${title}`);
    }
  });

task の下にさらに add.command() で作れると思っていませんでした。
そのため、add をコマンドとして定義するのではなく、文字列引数として受けて判定しようとしていました。

2. 解決

Commander.js では、.command("task") で作ったコマンドの下に、さらに .command("add <title>") を定義できます。

修正後のコードです。

import { Command } from "commander";

const program = new Command();

const task = program
  .command("task")
  .description("Task を操作する");
  
task
  .command("add <title>")
  .description("Task を追加する")
  .action((title) => {
    console.log(`Adding ${title}`);
  });

3. 学んだこと

task add のような階層を作りたいときは、add を文字列として判定するのではなく、task の下のコマンドとして定義した方が自然だと分かりました。

Commander.js を触り始めた人で、同じように困った人の助けになれば幸いです。

4. 参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?