Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
JavaScript CLI libraries turn the arguments typed after a command into options, flags, and handler calls inside a Node.js program. A parser reads that argument list and checks it against the commands and options the program declares. These libraries define the commands of build tools, deploy scripts, and code generators that developers and coding agents run from a terminal.
Popularity
Commander has the most monthly downloads in this comparison, at 2.9B.
export function lernaCLI(argv?: string | readonly string[], cwd?: string) {
const cli = yargs(argv, cwd);
return globalOptions(cli)
.usage("Usage: $0 <command> [options]")
.demandCommand(1, "A command is required. Pass --help to see all available commands and options.")
.recommendCommands()
.strict()
.fail((msg: string, err: any) => {
// certain yargs validations throw strings :P const actual = err || new Error(msg);
// ValidationErrors are already logged, as are package errors if (actual.name !== "ValidationError" && !actual.pkg) {
// the recommendCommands() message is too terse if (/Did you mean/.test(actual.message)) {
// TODO: refactor to address type issues // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore log.error("lerna", `Unknown command "${cli.parsed.argv._[0]}"`);
}
log.error("lerna", actual.message);
}
// exit non-zero so the CLI can be usefully chained cli.exit(actual.exitCode > 0 ? actual.exitCode : 1, actual);
})
.alias("h", "help")
.alias("v", "version")
.wrap(cli.terminalWidth()).epilogue(dedent`
When a command fails, all logs are written to lerna-debug.log in the current working directory.
For more information, check out the docs at https://lerna.js.org/docs/introduction
`);
}
argparse
Parses command-line arguments for Node.js with subcommands, as a port of Python's argparse.
Downloads / mo
1.4B
Stars
516
Last release
3.0.4
License
PSF-2.0
Limitations
No keyword arguments.Pass an options object where Python argparse takes keyword arguments.
export function buildCLI(argv) {
return meow(helpText, {
autoHelp: false,
autoVersion: false,
argv,
// NOTE: `meow()` infers flag types when passing a flag object with inline. // However, `checkInvalidCLIOptions()` also needs this flag object. // So, unfortunately, the return value type inference by `meow()` is unavailable here. // // @ts-expect-error -- TS2322: Type '{ allowEmptyInput: {...} }' is not assignable to type 'AnyFlags'. flags,
// NOTE: We must enable `allowUnknownFlags` because meow exits with `2` if `allowUnknownFlags` is disabled. // Instead, we use our different exit code with `checkInvalidCLIOptions()`. // See also https://github.com/sindresorhus/meow/blob/v12.0.1/source/validate.js#L75 allowUnknownFlags: true,
// NOTE: If CLI flags are unspecified (e.g., `--cache` nor `--no-cache`), we want to fall back to config properties (e.g., `cache`). booleanDefault: undefined,
importMeta: import.meta,
});
}
Citty
Builds command-line apps from command definitions with nested, lazily loaded subcommands.
Downloads / mo
190.8M
Stars
1.4K
Last release
0.2.2
License
MIT
Strengths
Built on util.parseArgs.Parsing runs on Node's native util.parseArgs with no dependencies.
export async function runOclifCommandById(
commandId: string,
args: string[],
opts: OclifCommandRunOptions,
): Promise<void> {
const config = await OclifConfig.load(opts.rootDir);
applyBrandedBin(config, opts.publicSandboxName);
const errorLine = opts.error ?? console.error;
const exit = opts.exit ?? ((code: number) => process.exit(code));
const originalArgv = process.argv;
const nativeArgv = [...commandId.split(":"), ...args];
process.argv = [originalArgv[0] ?? process.execPath, originalArgv[1] ?? CLI_NAME, ...nativeArgv];
try {
await config.runCommand(commandId, args);
} catch (error) {
const exitCode = getOclifExitCode(error);
if (exitCode === 0) {
// Only oclif's own ExitError(0) is an intentional graceful exit (e.g. // Command.exit(0) / --help — its message is the synthetic "EEXIT: 0", // which must stay silent). Keep that path at exit 0. if (isOclifExitError(error)) {
process.exitCode = 0;
return;
}
// #5974: any OTHER error that merely happens to carry oclif.exit === 0 // is a genuine failure that bubbled out of a command's run(). #2666 // stopped it being silently swallowed (exit 0 + empty output); here we // also refuse to report success for it — surface its message AND exit // non-zero so `$?` stays scriptable. Fall back to a generic line if // formatOclifError() returns empty so a blank message never reintroduces // the silent path. const message = formatOclifError(error) || "Command exited with no output.";
errorLine(` ${message}`);
process.exitCode = 1;
return;
}
if (isOclifParseError(error)) {
errorLine(` ${formatOclifError(error)}`);
exit(exitCode ?? 1);
}
// NCQ #3180: oclif's Command.exit(code) throws an ExitError carrying // `oclif.exit`. Treat that as a graceful exit with the requested code // so we don't leak a raw `at Object.exit (... /@oclif/core/...)` stack // trace to the user. Other oclif error classes (e.g. RequiredArgsError) // are left to bubble up so oclif's own handler still prints them. if (isOclifExitError(error) && typeof exitCode === "number") {
exit(exitCode);
}
throw error;
} finally {
process.argv = originalArgv;
}
}
Sade
Builds Node.js CLIs with git-like subcommands, option aliases, default values, and generated help text.
handler => {
const ENABLE_MODERN = process.env.MICROBUNDLE_MODERN !== 'false';
const DEFAULT_FORMATS = ENABLE_MODERN ? 'modern,esm,cjs,umd' : 'esm,cjs,umd';
const cmd = type => (str, opts) => {
opts.watch = opts.watch || type === 'watch';
opts.entries = toArray(str || opts.entry).concat(opts._);
if (typeof opts.compress !== 'undefined') {
// Convert `--compress true/false/1/0` to booleans: if (typeof opts.compress !== 'boolean') {
opts.compress = opts.compress !== 'false' && opts.compress !== '0';
}
} else {
// the default compress value is `true` for web, `false` for Node: opts.compress = opts.target !== 'node';
}
handler(opts);
};
let prog = sade('microbundle');
prog
.version(version)
.option('--entry, -i', 'Entry module(s)')
.option('--output, -o', 'Directory to place build files into')
.option(
'--format, -f',
`Only build specified formats (any of ${DEFAULT_FORMATS} or iife)`,
DEFAULT_FORMATS,
)
.option('--watch, -w', 'Rebuilds on any change', false)
.option(
'--pkg-main',
'Outputs files analog to package.json main entries',
true,
)
.option('--target', 'Specify your target environment (node or web)', 'web')
.option('--external', `Specify external dependencies, or 'none'`)
.option('--globals', `Specify globals dependencies, or 'none'`)
.example('--globals react=React,jquery=$')
.option('--define', 'Replace constants with hard-coded values')
.example('--define API_KEY=1234')
.option('--alias', `Map imports to different modules`)
.example('--alias react=preact')
.option(
'--compress',
'Compress output using Terser (default true when --target is web, false when --target is node)',
)
.example('build --target web --no-compress')
.option('--strict', 'Enforce undefined global context and add "use strict"')
.option('--name', 'Specify name exposed in UMD builds')
.option('--cwd', 'Use an alternative working directory', '.')
.option('--sourcemap', 'Generate source map')
.example("watch --no-sourcemap # don't generate sourcemaps")
.option('--raw', 'Show raw byte size', false)
.option('--jsx', 'A custom JSX pragma like React.createElement', 'h')
.option(
'--jsxFragment',
'A custom JSX fragment pragma like React.Fragment',
'Fragment',
)
.option(
'--jsxImportSource',
'Declares the module specifier to be used for importing jsx factory functions',
)
.option('--tsconfig', 'Specify the path to a custom tsconfig.json')
.example('build --tsconfig tsconfig.build.json')
.option(
'--generateTypes',
'Whether or not to generate types , if `types` or `typings` is set in `package.json` then it will default to be `true`',
)
.option('--css', 'Where to output CSS: "inline" or "external"', 'external')
.option(
'--css-modules',
'Turns on css-modules for all .css imports. Passing a string will override the scopeName. eg --css-modules="_[hash]"',
null,
)
.option(
'--workers',
'Bundle module workers - see https://github.com/surma/rollup-plugin-off-main-thread#auto-bundling',
false,
)
.option(
'--visualize',
'Generate bundle makeup visualization (stats.html)',
false,
);
prog
.command('build [...entries]', '', { default: true })
.describe('Build once and exit')
.action(cmd('build'));
prog
.command('watch [...entries]')
.describe('Rebuilds on any change')
.action(cmd('watch'));
// Parse argv; add extra aliases return argv =>
prog.parse(argv, {
alias: {
o: ['output', 'd'],
i: ['entry', 'entries', 'e'],
w: ['watch'],
},
boolean: ['generateTypes'],
});
}
FAQ
Commander builds command trees with options, handlers, and generated help, and it has the most monthly downloads, at 2.9B. yargs adds value coercion and validation, while oclif organizes larger CLIs as command classes with plugins.
Commander is a Node.js library for command-line programs. It defines commands, options, and action handlers, then parses the command line and prints generated help.
Commander defines command trees with a fluent API and needs parseAsync for asynchronous actions. yargs converts and validates option values during parsing with coerce and demandOption.
oclif builds class-based CLIs with command discovery and plugins, the structure behind the Salesforce CLI. Commander keeps commands in one fluent program definition.
Use parseAsync instead of parse when an action handler is asynchronous.
Declare the relevant key with string to prevent numeric or boolean interpretation.
For coding agents
Found your CLI library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.