Considering the Core Idea
I'm zeroing in on the essence of the user's needs. The core demand is a CLI boilerplate built with Node.js and Commander.js. I've been dissecting the core requirements and features most essential for creating a workable, well-structured, starting point for developers using this tech. I'm focusing on the essential elements, and how they fit together.
Defining the Essentials
I've been refining my focus on the bare minimum for the Node.js CLI boilerplate. Initially, I was thinking about colors and prompts. Now, I'm sticking with Commander.js and chalk as the baseline, recognizing that extras like inquirer can be added later. I'm prioritizing simplicity while providing useful building blocks for a functional CLI.
Outlining the Structure
My current focus is on the package.json setup, especially the "type": "module" and "bin" fields. I'm building out the entry point with the shebang and considering the modularity of the command structure. Now, I'm working with the Commander implementation itself, and deciding how to create sample commands for demonstration.
Building the CLI Structure
I'm now fully immersed in the code. I've got the package.json file in place, configuring "type": "module" and the "bin" entry. The foundational bin/index.js now uses Commander.js to structure command-line arguments. I've created a sample greet.js file to demonstrate a basic command, including argument parsing and the chalk library for styling.
Completing the Core Structure
I've finalized the CLI structure. package.json includes type:module and the bin entry point. In bin/index.js, I've implemented the program with Commander.js. The src/commands directory holds modular command logic. My focus now is on testing and usage instructions. I'm making sure to cover install, link, and run steps.
Documenting the Details
I'm now adding comprehensive comments to the code for clarity. I've also re-reviewed my package.json file, and confirmed that "type": "module" is essential for supporting chalk v5+ and later versions. It's critical to make this dependency crystal clear in the documentation. I'll make sure to mention specific versions. The final steps include the documentation of how to use the boilerplate.
Here is a modern, production-ready boilerplate for a Node.js CLI tool using Commander.js.
This boilerplate uses ES Modules (import/export) and includes a modular structure to keep your code clean as the app grows.
1. Project Structure
We will create the following file structure:
my-cli-tool/
├── bin/
│ └── index.js # The entry point (executable)
├── src/
│ ├── commands/ # Folder for specific command logic
│ │ └── greet.js
│ └── utils/ # Shared utilities (logs, helpers)
├── package.json
└── README.md
2. Setup & Installation
Run these commands in your terminal to create the folders and install dependencies:
mkdir my-cli-tool
cd my-cli-tool
npm init -y
npm install commander chalk
Note: We include chalk because almost every CLI needs colored output, and it pairs perfectly with Commander.
3. The Code
A. package.json
Update your package.json. Two keys are critical here:
"type": "module": Enables modern ES6 imports.
"bin": Tells Node where your executable file lives.
{
"name": "my-cli-tool",
"version": "1.0.0",
"description": "A Node.js CLI Boilerplate",
"main": "bin/index.js",
"type": "module",
"bin": {
"mytool": "./bin/index.js"
},
"dependencies": {
"chalk": "^5.3.0",
"commander": "^12.0.0"
}
}
B. src/commands/greet.js
Let's create a sample command functions. It's best practice to keep logic separate from the main declaration file.
import chalk from 'chalk';
export function greetCommand(name, options) {
let output = `Hello, ${name}!`;
if (options.capitalize) {
output = output.toUpperCase();
}
// Log with color
console.log(chalk.green(output));
if (options.debug) {
console.log(chalk.dim(`Debug: Called with name=${name}, options=${JSON.stringify(options)}`));
}
}
C. bin/index.js
This is your main entry point. It instantiates Commander, defines commands, and parses arguments.
Note: The first line #!/usr/bin/env node (the Shebang) is required for CLI tools to run in the shell.
#!/usr/bin/env node
import { Command } from 'commander';
import { greetCommand } from '../src/commands/greet.js';
// Initialize the program
const program = new Command();
// logical settings
program
.name('mytool')
.description('A boilerplate CLI tool using Commander.js')
.version('1.0.0');
// Define a command
program
.command('greet')
.description('Greets the user')
.argument('<string>', 'name of the person to greet')
.option('-c, --capitalize', 'Capitalize the greeting')
.option('-d, --debug', 'Show debug info')
.action((str, options) => {
greetCommand(str, options);
});
// Parse arguments
program.parse();
4. Testing Locally
To test your CLI without publishing it to npm, use npm link. This simulates a global installation on your machine.
-
In your project root, run:
npm link
-
Now you can run your command using the name defined in the bin section of package.json (mytool):
# Basic usage
mytool greet World
# With options
mytool greet Dave --capitalize
# View auto-generated help
mytool --help
5. Summary of Key Concepts used:
- Shebang (
#!/usr/bin/env node): Tells the operating system to use the installed Node.js runtime to execute the file.
- ESM (
type: "module"): Allows you to refrain from using require() and clean up the syntax.
- Arguments (
<string>): Required inputs (using <>) or optional inputs (using []).
- Options flags (
-c, --capitalize): Boolean flags or value flags passed to the action.
- Action Handler: The function that runs when the command matches.
6. Next Steps / Recommended Libraries
To expand this boilerplate, consider adding:
- Inquirer.js or @inquirer/prompts: For interactive input (lists, checkboxes, text input).
- Ora: For loading spinners if you perform async tasks (API calls).
- Boxen: To draw boxes around your output (great for welcome messages).