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.

useful-tricks-for-javascript

original article

Get Unique Values of an Array

Getting an array of unique values is probably easier than you think:

1
2
var j = [...new Set([1, 2, 3, 3])]
>> [1, 2, 3]

Array and Boolean

Ever need to filter falsy values (0, undefined, null, false, etc.) out of an array? You may not have known this trick:

1
2
3
4
5
6
7
myArray
.map(item => {
// ...
})
// Get rid of bad values
.filter(Boolean);
Just pass Boolean and all those falsy value go away!

Create Empty Objects

Sure you can create an object that seems empty with {}, but that object still has a proto and the usual hasOwnProperty and other object methods. There is a way, however, to create a pure “dictionary” object:

1
2
3
4
let dict = Object.create(null);

// dict.__proto__ === "undefined"
// No object properties exist until you add them

There are absolutely no keys or methods on that object that you don’t put there!

Get Query String Parameters

For years we wrote gross regular expressions to get query string values but those days are gone – enter the amazing URLSearchParams API:

1
2
3
4
5
6
7
8
9
// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);

console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"

Much easier than we used to fight with!