global-options-added.js
This file
Path
examples/global-options-added.js
52 lines · 1.7 KiB · JavaScript
Last changed by
Switching to esm-only (#2464)John Geebefore adoptionf4bd470
History of this fileTake it
Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 1–11why, one step back1#!/usr/bin/env node23// This example shows a couple of ways to add a "global" option to all of the subcommands.4// The first approach is to use a subclass and add the option as the subcommand is created.5// The second approach is to loop over the subcommands after they have been created.6//7// The code in this example assumes there is just one level of subcommands.8//9// (A different pattern for a "global" option is to add it to the root command, rather10// than to the subcommand. See global-options-nested.js.)11Switching to esm-only (#2464)John Geebefore adoptionf4bd470
line 12why, one step back12import { Command } from 'commander';Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 13–25why, one step back1314// Common options can be added when subcommands are created by using a custom subclass.15// If the options are unsorted in the help, these will appear first.16class MyRootCommand extends Command {17 createCommand(name) {18 const cmd = new Command(name);19 cmd.option('-v, --verbose', 'use verbose logging');20 return cmd;21 }22}2324const program = new MyRootCommand();25Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 26–27why, one step back26program27 .command('print')Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 28–32why, one step back28 .option('--a4', 'Use A4 sized paper')29 .action((options) => {30 console.log('print options: %O', options);31 });32Reformat code with Prettier (#2180)John Geebefore adoption1bdc749
lines 33–34why, one step back33program34 .command('serve')Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631
lines 35–52why, one step back35 .option('-p, --port <number>', 'port number for server')36 .action((options) => {37 console.log('serve options: %O', options);38 });3940// Common options can be added manually after setting up program and subcommands.41// If the options are unsorted in the help, these will appear last.42program.commands.forEach((cmd) => {43 cmd.option('-d, --debug');44});4546program.parse();4748// Try the following:49// node global-options-added.js --help50// node global-options-added.js print --help51// node global-options-added.js serve --help52// node global-options-added.js serve --debug --verbose