Writing a command-line executable with TypeScript

July 2017 July 2026
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!

Step 1: 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.

Quick interlude
Tax Wealth, Not Work
Your salary is taxed on every payslip; large fortunes mostly aren't. That gap is a big part of why housing feels out of reach. Gary Stevenson breaks it down better than anyone: watch on YouTube →

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 your package globally on a machine using:

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 ...

Tax Wealth, Not Work
Wages get taxed to the bone while the ultra-rich watch their assets compound untouched — and then buy up the houses you're saving for. If you work for your money, this is your fight too.
Watch on YouTube →