Used

How toUse package.json#bin to create a CLI

Let's say you want to have some scripts in your app that you need to run from time to time, maybe you're building a script to generate code or run another process.

Typically in JS, you will use the package.json's scripts options like this.

{
  "scripts": {
    "generate": "tsx scripts/generate.ts"
  }
}

Then run it with npm run generate.

But the package.json has a key bin that can be used to create scripts that we can later run using npx and we can point to a file in our application

{
  "bin": {
    "generate": "./scripts/generate.js"
  }
}

Then we can create our file and add the hashbang at the top.

#!/usr/bin/env node
console.log("running generate script");

And run it using npx generate.

And if we want to use TypeScript we could switch to use Bun instead of Node.

#!/usr/bin/env bun
console.log("running generate script");

Allowing us now to use a TS file and access to any Bun feature.

Combining this with other packages like arg and chalk we could build a complete CLI inside our project scripts folder and run it with npx as if it was a package we installed in our project.