Skip to content

Commit 1ef0a73

Browse files
committed
standardise Commander exports usage
BREAKING: this removes the `Commander` export from `lib/main.js`.
1 parent ca1bd81 commit 1ef0a73

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ The `@basd/cli` module is designed to be intuitive for developers familiar with
3636

3737
The `commander` module in `@basd/cli` is used for building command-line interfaces with support for commands, options, and sub-commands.
3838

39+
Keeping inline with Commander's own recommendations for [declaring the `program` variable](https://github.com/tj/commander.js/tree/v11.1.0?tab=readme-ov-file#declaring-program-variable), this presents two ways to create an instance:
40+
41+
For simpler CLI applications, where everything fits easily in one file:
42+
3943
```js
4044
const { program } = require('@basd/cli')
4145

@@ -54,6 +58,41 @@ program
5458
program.parse(process.argv)
5559
```
5660

61+
For more complex application, where you have the need to spread logic out across multiple files:
62+
63+
```js
64+
// main.js
65+
const { Command } = require('@basd/cli')
66+
const program = new Command()
67+
68+
// Attach subcommand
69+
const { addServeCommand } = require("./serve")
70+
addServeCommand(program);
71+
72+
// Parse command-line arguments
73+
program.parse(process.argv)
74+
```
75+
76+
```js
77+
// serve.js
78+
function addServeCommand(program) {
79+
// Define a new command with options
80+
return program
81+
.command('serve [port]')
82+
.description('Start the server')
83+
.option('-d, --debug', 'output extra debugging')
84+
.action((port, options) => {
85+
const portNumber = port || 3000
86+
console.log(`Server running on port ${portNumber}`)
87+
if (options.debug) console.log('Debugging mode is on')
88+
})
89+
}
90+
91+
module.exports = {
92+
addServeCommand
93+
}
94+
```
95+
5796
### ShellJS
5897

5998
`ShellJS` is integrated for executing shell commands in a Unix shell-style, but within your Node.js scripts.

lib/main.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ const colors = require('cli-color')
3838
* @link https://npmjs.com/package/commander
3939
* @type {Object}
4040
*/
41-
const Commander = require('commander')
41+
const { program, Command } = require('commander')
4242

4343

4444
/**
@@ -53,8 +53,8 @@ const { Spinner, spinner, Progress } = require('@basd/spinner')
5353
// Module Augmentation
5454

5555
// Assigning imported modules to the cli object for unified export.
56-
cli.Commander = Commander
57-
cli.program = Commander.program // Export Commander.js singleton instance
56+
cli.Command = Command
57+
cli.program = program
5858
cli.Progress = Progress
5959
cli.Spinner = Spinner
6060
cli.spinner = spinner

0 commit comments

Comments
 (0)