Introduction
tsargp is a command-line argument parsing library that helps you write clean code.
Features
Usability | Functionality | Presentation |
---|---|---|
Zero-dependency | Word completion | Help message formatting |
Fully declarative | Option validation | Text wrapping/alignment |
Type-checked | Option requirements | Paragraphs and lists |
Browser-compatible | Value normalization | SGR (opens in a new tab) colors and styles |
35KB minified | Name suggestions | Custom phrasing |
ESM-native | Nested commands | Option grouping/hiding |
Online documentation | Asynchronous callbacks | Help sections and usage |
GNU's short-options | JSON, CSV and Markdown |
Motivation
Why use this library when there are already many good argument parsers on npm?
Its most distinctive feature is a declarative API. Very few libraries on npm that we know of (at
the time of writing) have this feature (worth mentioning meow (opens in a new tab), yargs (opens in a new tab) and oclif (opens in a new tab)). Most others
have either imperative or fluent interface, whereas tsargp offers a way to declare all of your
command-line options in a single object
.
Furthermore, by using TypeScript, it ensures that the values resulting from argument parsing have accurate data types, i.e., they reflect the attributes specified in the options' definitions. In particular, an option's value will be a union literal if you declare an enumeration constraint in its definition. Even JSDoc comments are preserved in IntelliSense!
Installation
npm install tsargp
Quick Start
Define your command-line options. We recommend placing them in a separate file:
import { type Options, ... } from 'tsargp';
export default {
// define the options' attributes...
} as const satisfies Options;
Import them in your main script:
#!/usr/bin/env node
import { ArgumentParser } from 'tsargp';
import options from './<your_cli_name>.options.js';
try {
const parser = new ArgumentParser(options);
await parser.validate(); // validate the option definitions (you can skip this in production)
const values = await parser.parse(); // use this to get the options' values
// await parser.parseInto(myValues); // use this to fill an existing object or class instance
} catch (err) {
if (err instanceof Error) {
console.error(`${err}`); // genuine errors
process.exitCode = 1;
} else {
console.log(`${err}`); // help message, version or completion words
}
}
Optionally, enable word completion:
complete -o default -C <path_to_main_script> <your_cli_name>