Define global and command-specific options with various types, defaults, and validation patterns.
Add options that apply to all commands in the CLI.
/**
* Add a global option available to all commands
* @param rawName - Option name(s) with optional value like '--output, -o <file>'
* @param description - Option description for help
* @param config - Optional configuration
* @returns CLI instance for chaining
*/
option(rawName: string, description: string, config?: OptionConfig): CAC;
interface OptionConfig {
/** Default value for the option */
default?: any;
/** Type transformation array (e.g., [String], [Number]) */
type?: any[];
}Usage Examples:
// Boolean flag
cli.option("--verbose", "Enable verbose output");
// Option with value
cli.option("--output <file>", "Output file path");
// Option with optional value
cli.option("--port [port]", "Server port", { default: 3000 });
// Short and long forms
cli.option("-o, --output <file>", "Output file");
// Option with type transformation
cli.option("--numbers <nums>", "Number list", {
type: [Number],
default: [1, 2, 3]
});Add options that only apply to a specific command.
/**
* Add option to a specific command
* @param rawName - Option name(s) with optional value
* @param description - Option description
* @param config - Optional configuration
* @returns Command instance for chaining
*/
Command.prototype.option(rawName: string, description: string, config?: OptionConfig): Command;Usage Examples:
cli
.command("build <entry>", "Build application")
.option("--minify", "Minify output")
.option("--source-map", "Generate source maps")
.option("--target <target>", "Build target", { default: "es2015" })
.action((entry, options) => {
if (options.minify) console.log("Minifying...");
if (options.sourceMap) console.log("Generating source maps...");
console.log(`Target: ${options.target}`);
});CAC supports various option name patterns and value types.
/**
* Option name patterns:
* - --flag: Boolean flag
* - --option <value>: Required value (angled brackets)
* - --option [value]: Optional value (square brackets)
* - -s, --long: Short and long forms
* - --no-flag: Negated boolean option
*/Pattern Examples:
// Boolean flags
cli.option("--help", "Show help");
cli.option("--no-colors", "Disable colors");
// Required values
cli.option("--config <file>", "Config file path");
cli.option("--port <number>", "Port number");
// Optional values
cli.option("--log-level [level]", "Log level", { default: "info" });
// Short and long forms
cli.option("-v, --verbose", "Verbose output");
cli.option("-o, --output <file>", "Output file");
// Negated options (automatically creates --no- variant)
cli.option("--colors", "Enable colors", { default: true });
// This also creates --no-colors that sets colors to falseSupport for dot-notation in option names for nested configuration.
/**
* Dot-nested options allow setting nested object properties
* Example: --env.API_KEY value sets options.env.API_KEY = value
*/Usage Examples:
cli.option("--env.* <value>", "Environment variables");
// Command line: --env.API_KEY=secret --env.DEBUG=true
// Results in: { env: { API_KEY: "secret", DEBUG: "true" } }
// Usage in action
cli
.command("deploy", "Deploy application")
.option("--config.* <value>", "Configuration values")
.action((options) => {
console.log(options.config); // { host: "localhost", port: "3000" }
});Options that accept multiple values to create arrays.
/**
* Multiple occurrences of the same option create arrays
* Type transformations can be applied to array elements
*/Usage Examples:
// String arrays
cli.option("--include <pattern>", "Include patterns");
// Command line: --include "*.js" --include "*.ts"
// Result: { include: ["*.js", "*.ts"] }
// Typed arrays
cli.option("--ports <numbers>", "Port numbers", { type: [Number] });
// Command line: --ports 3000 --ports 4000
// Result: { ports: [3000, 4000] }Advanced option configuration with defaults and type transformations.
interface OptionConfig {
/** Default value when option is not provided */
default?: any;
/** Type transformation array for converting string values */
type?: any[];
}Configuration Examples:
// Default values
cli.option("--port [port]", "Server port", {
default: 3000
});
// Type transformations
cli.option("--timeout <ms>", "Timeout in milliseconds", {
type: [Number],
default: 5000
});
// String transformation
cli.option("--name <name>", "Your name", {
type: [String],
default: "Anonymous"
});
// Custom transformation function
cli.option("--json <data>", "JSON data", {
type: [JSON.parse]
});The Option class represents individual options with their metadata.
class Option {
/** Primary option name */
readonly name: string;
/** All option names including aliases */
readonly names: string[];
/** Whether option is a boolean flag */
readonly isBoolean?: boolean;
/** Whether option value is required */
readonly required?: boolean;
/** Option configuration */
readonly config: OptionConfig;
/** Whether option is negated (--no- prefix) */
readonly negated: boolean;
/** Raw option name as specified */
readonly rawName: string;
/** Option description */
readonly description: string;
/**
* Option constructor
* @param rawName - Raw option name with flags like '--output, -o <file>'
* @param description - Option description
* @param config - Optional configuration
*/
constructor(rawName: string, description: string, config?: OptionConfig);
}How CAC processes and normalizes option names.
/**
* Option name processing rules:
* - Kebab-case options are converted to camelCase in code
* - --clear-screen becomes options.clearScreen
* - Both --clear-screen and --clearScreen work in CLI
* - Shortest name is used for aliases, longest for primary name
*/Name Processing Examples:
cli
.command("dev", "Development server")
.option("--clear-screen", "Clear screen on rebuild")
.action((options) => {
// Access via camelCase
if (options.clearScreen) {
console.clear();
}
});
// Both work on command line:
// my-cli dev --clear-screen
// my-cli dev --clearScreenRuntime validation and error handling for options.
/**
* CAC performs automatic validation:
* - Required option values must be provided
* - Unknown options trigger errors (unless allowed)
* - Type transformations are applied automatically
*/Validation Examples:
// This will throw CACError if <file> is not provided
cli.option("--config <file>", "Config file path");
// This allows the option to be a boolean flag or have a value
cli.option("--log [level]", "Enable logging", { default: "info" });
// Unknown option handling
cli
.command("build", "Build project")
.allowUnknownOptions() // Allows unknown options for this command
.action((options) => {
// options may contain unknown properties
});Options work seamlessly with the command system:
// Global options available to all commands
cli.option("--verbose", "Verbose output");
cli.option("--config <file>", "Config file");
// Command-specific options
cli
.command("build <entry>", "Build application")
.option("--minify", "Minify output")
.option("--watch", "Watch for changes")
.action((entry, options) => {
// Access to both global and command options
if (options.verbose) console.log("Verbose mode enabled");
if (options.config) console.log(`Using config: ${options.config}`);
if (options.minify) console.log("Minifying output");
if (options.watch) console.log("Watching for changes");
});/**
* Option-related errors:
* - Missing required option values
* - Unknown options (when not allowed)
* - Type conversion failures
*/Common error scenarios:
// Missing required value
// Command: my-cli --output
// Error: option `--output` value is missing
// Unknown option
// Command: my-cli --unknown-flag
// Error: Unknown option `--unknown-flag`
// Type conversion error with custom type function
cli.option("--json <data>", "JSON data", { type: [JSON.parse] });
// Command: my-cli --json "invalid json"
// Error: Invalid JSON in --json option