Skip to main content

Yargs · TypeScript · Open source

Your files are
your command tree.

Stop maintaining a central list of commands. Put each command in its own file, let the path define where it lives, and keep the Yargs options, middleware and help output you already use.

src/cli.ts
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import { fileCommands } from 'yargs-file-commands';

await yargs(hideBin(process.argv))
  .command(
    await fileCommands({
      commandDirs: [import.meta.dirname + '/commands'],
    }),
  )
  .demandCommand(1)
  .help()
  .parseAsync();
01Add a file

commands/db/health.ts

02Get a command

db health, no registration

03Describe groups

A command.ts per directory

04Validate in CI

One test checks the whole tree

Less registration. More building.

Add a file.
Get a command.

Folders become groups and dotted names keep small trees compact. defineCommand infers the handler arguments from your Yargs builder, so argv.port is a number without a cast.

Learn the file conventions
commands/
├── db/
│   ├── health.ts       → db health
│   └── migration/
│       └── command.ts  → db migration
├── studio.start.ts     → studio start
└── $default.ts         → default command

// studio.start.ts
export const command = defineCommand({
  describe: 'Start the studio',
  builder: (yargs) =>
    yargs.option('port', { type: 'number', default: 3000 }),
  handler: (argv) => console.log(argv.port),
});

Built for CLIs that keep growing

Load what runs.
Test what ships.

The tree is scanned once, but a group imports its commands only when Yargs enters it. Because a broken module in an unvisited group would otherwise hide, validateCommands imports every command in a test and checks the positional arguments, without running a handler.

Validate your treeLayer generated commands →
import { validateCommands } from 'yargs-file-commands';

it('validates the complete command tree', async () => {
  await expect(
    validateCommands({
      commandDirs: [import.meta.dirname + '/commands'],
    }),
  ).resolves.toBeUndefined();
});

Keep reading

Find your way around.

Short guides for the conventions, plus an API reference generated from the library source.

Install

From a folder of files to a working CLI.

npm install yargs-file-commands yargs

ESM only. Requires Node.js 22 or newer and Yargs 18.