{"id":17524,"library":"clap","title":"Clap.js CLI Argument Parser","description":"Clap.js is a robust library for Node.js designed to simplify the creation of command-line interfaces (CLIs). It provides a fluent API for defining commands, options, and arguments, supporting advanced features like argument coercion, completion suggestions, and sub-commands. The library aims to facilitate both simple CLI tools and complex applications with deep command hierarchies. Inspired by Commander.js, Clap.js focuses on ease of use and flexibility. The current stable version is 3.1.1, with recent releases addressing regressions and refining API signatures. Since version 3.0.0, it supports both ESM and CommonJS (dual module) and targets Node.js versions `^12.20.0`, `^14.13.0`, and `>=15.0.0`. It offers a structured approach to argv processing and context management for developers building intricate command-line tools.","status":"active","version":"3.1.1","language":"javascript","source_language":"en","source_url":"https://github.com/lahmatiy/clap","tags":["javascript","cli","command","option","argument","completion"],"install":[{"cmd":"npm install clap","lang":"bash","label":"npm"},{"cmd":"yarn add clap","lang":"bash","label":"yarn"},{"cmd":"pnpm add clap","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary factory function for creating new Command instances. Preferred ESM usage for direct named imports since v3. For CommonJS, use `const { command } = require('clap');`","wrong":"const { command } = require('clap'); // In ESM context, use import","symbol":"command","correct":"import { command } from 'clap';"},{"note":"The main module export. For ESM, the default export is an object containing the `command` method. For CommonJS, `require('clap')` returns this object, typically aliased as `cli`.","wrong":"import { clap } from 'clap';","symbol":"clap","correct":"import clap from 'clap';\n// or\nconst cli = require('clap');"},{"note":"The underlying Command class, available as a named export since v3, for advanced scenarios like extending its functionality or type hinting.","wrong":"const Command = require('clap').Command;","symbol":"Command","correct":"import { Command } from 'clap';"}],"quickstart":{"code":"import { command } from 'clap';\n\nconst myCommand = command('my-command [optional-arg]')\n    .description('An example CLI command with various options and sub-commands.')\n    .version('1.2.3')\n    .option('-b, --bool', 'A boolean option that can be toggled.')\n    .option('--foo <foo>', 'An option that requires an argument.')\n    .option('--bar [bar]', 'An option that can optionally take an argument.')\n    .option('--baz [value]', 'An option with an optional argument and a normalize function.',\n        value => Number(value) || 0,\n        123 // 123 is default if no value provided\n    )\n    .action(function({ options, args, literalArgs }) {\n        console.log('Command executed!');\n        console.log('Options:', options);\n        console.log('Arguments:', args);\n        console.log('Literal Args (after --):', literalArgs);\n        if (options.bool) {\n          console.log('Boolean option --bool was enabled.');\n        }\n    });\n\n// Define a sub-command\nmyCommand\n    .command('nested <name>')\n        .description('A nested sub-command demonstrating hierarchy.')\n        .option('-q, --quz', 'A parameter specific to the nested command.', 'Default value for quz')\n        .action(({ args, options }) => {\n            console.log(`Executing nested command for ${args.name}`);\n            console.log('Nested options:', options);\n        })\n        .end(); // Go back to the parent command context\n\n// Simulate running with arguments, e.g., process.argv.slice(2)\nmyCommand.run(['--foo', 'hello', '-b', 'arg1', '--', 'literal1', 'literal2']);\nmyCommand.run(['nested', 'user-name', '-q']);\n","lang":"typescript","description":"Demonstrates basic CLI setup with options, arguments, version, description, sub-commands, and an action function to process parsed values."},"warnings":[{"fix":"Ensure your project is configured for ESM (e.g., `\"type\": \"module\"` in package.json) or use appropriate CommonJS imports. Update Node.js to a supported version.","message":"Clap.js converted to pure ESM (ECMAScript Modules) since v3.0.0. While CommonJS is supported via dual module, direct CommonJS `require()` statements might behave differently or require updates to import paths. Node.js version requirements also changed to `^12.20.0`, `^14.13.0`, and `>=15.0.0`.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Refactor `command()` calls to only pass the usage string as the first parameter (e.g., `command('my-command [arg1]')`). Ensure no additional parameters are provided.","message":"The `command()` function's signature changed in v3.1.0, removing all parameters except the first (`usage`). Earlier v3.0.0-beta.1 also changed `Command`'s constructor and `Command#command(method)` to take `usage` only (e.g., `command('name [param]')` instead of `command('name', '[param]')`). Passing additional parameters will now throw an error.","severity":"breaking","affected_versions":">=3.0.0-beta.1"},{"fix":"Upgrade Node.js to version 8 or higher. If migrating from v1, review method names like `create()` which are no longer part of the public API in current versions.","message":"Support for Node.js versions older than 8 was dropped in v2.0.0. Additionally, the `create()` method was renamed in v2.0.0 (though the current API uses `command()`).","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Consult the `.option()` API documentation carefully for the correct usage patterns and argument definitions, particularly for `normalize` and `default` values.","message":"When defining options with optional arguments, ensure proper usage syntax, e.g., `--bar [bar]`. Misconfigured option definitions can lead to unexpected parsing behavior or incorrect value assignment, especially when using `normalize` functions.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure the `command()` method receives only one string parameter, representing the command's usage (e.g., `command('my-command [arg]')`).","cause":"Attempting to define a command with multiple parameters after v3.0.0-beta.1/v3.1.0 changes.","error":"Error: Command definition expected to be a string or a command instance, got [object Object]"},{"fix":"Migrate your import statements to ESM `import { command } from 'clap';` or `import cli from 'clap';`.","cause":"Using CommonJS `require()` syntax within an ESM module context (e.g., in a `.mjs` file or a file where `type: module` is set in `package.json`).","error":"ReferenceError: require is not defined"},{"fix":"For ESM, use `import { command } from 'clap';` if `command` is a named export, or `import cli from 'clap';` then access via `cli.command(...)` if it's a method on the default export.","cause":"Incorrect ESM import, often trying `import { cli } from 'clap';` when `cli` is not a named export but rather a common alias for the default export, or attempting to destructure `command` from a module that exports it as a property of its default export.","error":"TypeError: cli.command is not a function"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}