Writing a command-line executable with TypeScript

July 2017
On the main tutorial we've setup the library 'hwrld'. Now we're going to learn how to make a library available as a system command. Actually, once you've completed the main tutorial, this becomes really easy. Just two simple steps!

Step1: Add execution instructions

On top of your executable files (the main files), add the following line:

#!/usr/bin/env node

This makes sure the system understands how to execute the compiled javascript file, by instructing it to interpret it with node.

Step 2: Modify the package.json

The package.json just needs to be modified a bit, so it looks like this:

typescript-library/package.json
{
  "name": "hwrld",
  "version": "1.0.0",
  "description": "Can log \"hello world\" and \"goodbye world\" to the console!",
  "main": "dist/index.js",
  "bin": {
      "hwrld": "dist/index.js"
  },
  "types": "dist/index.d.ts"
}

And voilà! Once you publish this, you will be able to install you're package globally on a machine using:

sudo npm install -g hwrld

Of course for the hwrld package this is pretty useless. A really simple yet instructive example I've written is a controller for the mpc music player. You can find the code here: https://github.com/bersling/mpc-control.

By the way, there wasn't really anything typescripty about this tutorial, it holds just as well for plain javascript node modules!

You can now ...

Interested in full stack TypeScript?