danielkhoo.io

twitter

github

NPM CLI Template

Every developer collects their own toolbox of odd bash util scripts lying around. Typically I shove it in .zshrc or .bashrc for easy portability. But since using Claude to translate scripts is extremely handy I've been experimenting with translating them into node.js scripts so they can be invoked anywhere with a simple npx command.


Having done this a few times (nixtime), I made a template repo along with the steps to initialize and deploy it to npm.

https://github.com/danielkhoo/npm-cli-template


Step 1: Clone the template repo

git clone https://github.com/danielkhoo/npm-cli-template.git


Step 2: Implement your logic

The dummy code in "cli.js" is a simple hello-world script

#!/usr/bin/env node

const yargs = require('yargs/yargs');

const argv = yargs(process.argv.slice(2))
  .option('n', {
    alias: 'name',
    describe: 'Name to greet',
    type: 'string',
  })
  .usage('Usage: $0 [-n name]')
  .example('$0', 'Print "Hello World"')
  .example('$0 -n Alice', 'Print "Hello Alice"')
  .help('h')
  .alias('h', 'help').argv;

const name = argv.name || 'World';

async function run() {
  try {
    // TODO: Implement the logic for the CLI
    console.log(`Hello ${name}!`);
  } catch (error) {
    console.error('Error:', error.message);
    process.exit(1);
  }
}

run();

Step 3: Test the script

To test the cli before publishing, link the package to locally

npm link <name-of-package>

Then invoke it with npx

npx <name-of-package>

Step 4: Deploy to NPM

Create an npm account if you don't have one. You'll need to login via the cli.

npm login

Finally publish the package

npm publish