An open API service indexing awesome lists of open source software.

https://github.com/danielpza/commander-register

Extends commander.js with a fastify-like plugin `register` api
https://github.com/danielpza/commander-register

commander commanderjs javascript node nodejs plugin register

Last synced: 22 days ago
JSON representation

Extends commander.js with a fastify-like plugin `register` api

Awesome Lists containing this project

README

          

# commander-register

Extends [commander.js](https://github.com/tj/commander.js) with a fastify-like plugin `register` api.

Features:

- **type safety:** plugins that extend the command instance are supported.
- **lightweight:** no dependencies needed.
- **familiar:** similar api to fastify's register api

Example:

```js
import { Command } from "commander";
import "commander-register/patch";

new Command()
.option("-c, --compress")
.command("sub-command")
.register(prettyErrors)
.register(setMeta)
.register(logger)
.action(() => {
// noop
})
.parse();
```

See [./examples/plugins.mjs](./examples/plugins.mjs)

## Installation

```sh
npm install commander-register
pnpm install commander-register
yarn add commander-register
```

## Setup

Import `commander-register/patch` once at the entry point of your app. It patches `Command.prototype` with the `register` method. All `Command` instances (including those created via `createCommand`) will have `register` available.

```js
import "commander-register/patch";
import { Command, program } from "commander";

program.register(prettyErrorsPlugin).parse();

const command = new Command();
command.register(loggerPlugin);
```

### Applying the patch using `node --import`

You can also apply the patch globally using Node's `--import` flag:

```sh
node --import commander-register/patch your-app.js
```

## Plugins

Use `command.register(plugin)` to modify command behavior. `plugin` is a function that receives the `Command` object.

Example:

```js
program.register(prettyErrors).parse();

function prettyErrors(command) {
command.configureOutput({
/* snip */
});
}
```

### Extending command instance with more functionality

Return the instance from the plugin to let TypeScript infer the newly added methods:

```js
program.register(helloWorldPlugin).helloWorld().parse();

function helloWorldPlugin(command) {
return Object.assign(command, {
helloWorld() {
console.log("Hello World");
return this;
},
});
}
```

### defineCommanderPlugin

Use the `defineCommanderPlugin` helper to ensure type safety when creating plugins:

```js
import { defineCommanderPlugin } from "commander-register";

export const prettyErrors = defineCommanderPlugin((command) => {
command.configureOutput({
/* snip */
});
});
```

## Resources

- https://github.com/tj/commander.js/issues/2505 - Plugin API discussion in commander.js
- https://github.com/tj/commander.js/pull/2503 - Pull request adding this plugin to commander.js codebase.