Create a Hybrid Single-Multi Command Node.js CLI with Oclif and TypeScript

Shawn Wang
InstructorShawn Wang

Share this video with your friends

Send Tweet

Sometimes you still want to support the API and quick developer experience of a single command, while still supporting multi commands in your CLI. This is handy when, for example, you want your user to do something useful with just npx mycli.

Here's a quick hack that lets you do that, while also deepening your understanding of how your CLI works with TypeScript, Node.js and Oclif under the hood.

Stephen Weiss
Stephen Weiss
~ 7 months ago

Is there a reason to not create the hybrid by checking if we only have two elements in argv instead of checking more? The concern I have with this approach is that we need to maintain a list of the registeredCommands which feels very easy to get out of sync.

On the other hand, we could flip this so that we have a base if no additional arguments are passed and otherwise use the standard behavior:

if (process.argv.length == 2) {
  require(`../${dev ? "src" : "lib"}/commands/init`)
} else {
  require(`../${dev ? "src" : "lib"}`)