commander-register
v0.1.0
Published
Extends commander.js with a fastify-like plugin `register` api
Readme
commander-register
Extends 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:
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();Installation
npm install commander-register
pnpm install commander-register
yarn add commander-registerSetup
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.
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:
node --import commander-register/patch your-app.jsPlugins
Use command.register(plugin) to modify command behavior. plugin is a function that receives the Command object.
Example:
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:
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:
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.
