Create cli tool with typescript

How to create a node.js cli tool with typescript:

  1. Specify a JavaScript file for bin in package.json
1
2
3
4
"name": "some-cli-tool-name",
"bin": {
"some-cli-tool-name": "./bin.js"
},
  1. Create ./bin.js
1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env node

// Register `ts-node` into node.js environment with a project option,
// cli will throw `Cannot use import statement outside a module ts-node` if `project` not is not found.
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.json')
});

// Run cli
require('./src/index.ts');
  1. Add shebang for node at the top of ./src/index.ts,
1
2
3
4
#!/usr/bin/env ts-node

const message: string = 'It works!';
console.log(message);
  1. Create tsconfig.json and fill with configuration.

  2. Write your cli tool with typescript.

  3. Publish to npm.

  4. Done.

Using npx to run the cli tool you just write in typescript.
npx some-cli-tool-name

NOTICE:

ALL TYPESCRIPT DEPENDENCIES MUST ADD TO "dependencies" IN package.json . LIKE: typescript ITSELF AND @types/* TYPE DEFINITIONS.