I’m often thinking about how to set up a CLI. First, I need to set "bin" in the package.json and make the file executable with a shebang. The user might want features like handling --version and --help automatically, along with options for config and logging.
To create a reusable boilerplate, I should design a minimal but structured template with files like index.js to initialize Commander and register commands like hello and init. The structure will include essential components to show the pattern clearly.Choosing CommonJS or ESM
I’m settling on using CommonJS for the CLI, so let’s outline the package.json. I want it to include basic information like name, version, and description, along with bin settings pointing to my CLI file.
However, there's a conflict with using chalk version 5 since it’s ESM-only. I have two options: either stick with chalk@4 for CommonJS support or switch entirely to ESM. I’m inclined to use ESM to keep it modern and utilize the latest features from chalk. I’ll structure the necessary files accordingly.Exploring Top-Level Await
I’m considering whether to use top-level await in my CLI. With Node 18+, I can import at the top and write a simple script using #!/usr/bin/env node followed by import { run } from '../src/index.js';. However, I note that Node may treat the shebang as a comment, which is fine.
When getting the version from package.json, I have to ensure support for JSON modules. While I could do that, I might prefer to set the version manually or use createRequire from CommonJS instead. I want to keep it simple and clear!Building the CLI with JSON Import
Many CLI tools now use JSON import, and with Node 20, it's the standard. To simplify, I’ll set up a program using const program = new Command(); and hardcode the version to '0.1.0', allowing users to adjust it later.
I'll add a sample hello command that can greet a user, providing an option for uppercase output. Using program.parseAsync(process.argv); is key for async actions, and I want to ensure it handles unknown commands gracefully. I also plan to support global options like --debug, keeping everything straightforward while illustrating best practices.Creating a Node.js CLI Boilerplate
In the run function, I'll set it up to call await program.parseAsync(argv); after building the program. Using Commander 8+, I can create a custom global error handler with .configureOutput for error styling.
Next, I’ll define my hello command in separate files and use import to bring in the necessary functions. The package.json will detail dependencies, and I'll include simple instructions for the user to create the project structure. I'll remember to mention setting executable permissions and that Node 16+ is required for ESM! Let’s keep everything streamlined. Here’s a simple, structured boilerplate for a Node.js CLI built with Commander.js.
import { Command } from 'commander';
import chalk from 'chalk';
import { createHelloCommand } from './commands/hello.js';
export async function run(argv = process.argv) {
const program = new Command();
program
.name('my-cli')
.description('Example CLI built with Commander.js')
.version('0.1.0');
// Global options
program
.option('-d, --debug', 'enable debug output')
.hook('preAction', (thisCommand, actionCommand) => {
const opts = thisCommand.opts();
if (opts.debug) {
process.env.DEBUG = '1';
console.error(
chalk.gray(`Debug mode enabled (running command: ${actionCommand.name()})`)
);
}
});
// Register subcommands
program.addCommand(createHelloCommand());
// Parse & execute
await program.parseAsync(argv);
}
5. src/commands/hello.js (example command)
js
import { Command } from 'commander';
import chalk from 'chalk';
export function createHelloCommand() {
const cmd = new Command('hello');
cmd
.description('Say hello')
.argument('[name]', 'Name to greet', 'world')
.option('-u, --uppercase', 'Output in upper case')
.action(helloAction);
return cmd;
}
async function helloAction(name, options) {
let message = `Hello, ${name}!`;
if (options.uppercase) {
message = message.toUpperCase();
}
console.log(chalk.green(message));
}
6. Running the CLI
From the project root:
bash
# Directly with Node
node bin/my-cli.js hello
node bin/my-cli.js hello Alice --uppercase
# Using npm scripts
npm start -- hello Bob
# Temporarily link as a global command
npm link
my-cli hello Charlie
my-cli --debug hello Dave
You can now add more commands by creating files in src/commands/ and registering them in src/index.js with program.addCommand(...).