Documentation
Introduction

Introduction

tsargp is a command-line argument parsing library that helps you write clean code.

Features

UsabilityFunctionalityPresentation
Zero-dependencyWord completionHelp message formatting
Fully declarativeOption validationText wrapping/alignment
Type-checkedOption requirementsParagraphs and lists
Browser-compatibleValue normalizationSGR (opens in a new tab) colors and styles
35KB minifiedName suggestionsCustom phrasing
ESM-nativeNested commandsOption grouping/hiding
Online documentationAsynchronous callbacksHelp sections and usage
GNU's short-optionsJSON, 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:

<your_cli_name>.options.ts
import { type Options, ... } from 'tsargp';
 
export default {
  // define the options' attributes...
} as const satisfies Options;

Import them in your main script:

<your_cli_name>.ts
#!/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>