This article describes how to build a typescript-based Nodejs command-line development environment.

Why use TypeScript

First, one of the biggest benefits of using TypeScript for writing libraries or tools is that it provides a typing mechanism that prevents us from making silly mistakes.

Second, with editors such as VS Code, TypeScript provides powerful Code hints. We don’t need to remember many API uses, and the editor automatically prompts us as we write Code. For example, when HTTP is introduced, typing HTTP. Prompts you for the various methods and properties you can use, with detailed explanations.

We strongly recommend using VS Code for TypeScript and Nodejs development.

Finally, using TypeScript is the trend, and many large companies are pushing TypeScript. Developing with TypeScript makes us more familiar with TS.

Initialization engineering

To build the command line tool, you need to create an NPM package. The NPM tool will be used to initialize the package and install the dependencies below.

First create a folder, then run the initialization command:

mkdir ts-node-demo && cd ts-node-demo
npm init
Copy the code

A series of prompts will appear on the console, just type as required, then press Enter, and type Yes when finished.

Package name: (typescript-CLI) Version: (1.0.0) Description: a CLIin typescript
entry point: (index.js) 
test command: 
git repository: 
keywords: CLI,TypeScript
author: YourName
license: (ISC) MIT
Copy the code

A package.json file will appear in the local folder after initialization. Our NPM package is already initialized. To avoid mispublishing, we make a change in package.json:

- private: false,
+ private: true,
Copy the code

Initialize the Git

Run in current directory:

git init
Copy the code

Then create a.gitignore file in the current directory and specify to ignore the node_modules folder:

node_modules/
lib/
Copy the code

Introducing Node types

Since we are developing Nodejs programs, we need to import the Nodejs type file in order to get the appropriate type checksum code hints:

npm i -D @types/node
Copy the code

Introducing the typescript

npm i typescript
Copy the code

You then need to initialize the tsconfig file.

./node_modules/.bin/tsc --init
Copy the code

The above command creates a tsconfig file under the current folder that guides TypeScript compilation. There are a lot of configuration items in it, and they are explained in great detail. We made two changes to fit our project:

+ "sourceMap": true,
+ "outDir": "lib",
Copy the code

This configuration specifies that the sourceMap file is generated and TypeScript compilation results are printed to the./lib folder.

Then add options level to compilerOptions:

"compilerOptions": {
    ...
},
+ "include": [
+ "src/**/*"
+]
Copy the code

This means we will only compile.ts files in the SRC directory.

Write the code

Create SRC folder under current directory and create index.ts:

mkdir src && echo "console.log('Your cli is running.');" > src/index.ts
Copy the code

Then run:

./node_modules/.bin/tsc 
Copy the code

You can find the lib/ directory under the folder, which contains the index.ts compiled JS file.

Creating a run script

The TSC command in node_modules needs to be referenced for each compilation. There are three ways to solve this problem:

  1. Install typescript packages globally:
npm i typescript -g
Copy the code

You can use the TSC command directly.

  1. usenpxperform

NPX is a command provided by NPM, which automatically downloads the corresponding package and executes it.

npx tsc
Copy the code
  1. Create the NPM script

Add a line of script to script in package.json:

"script": {
+ "build": "tsc"
}
Copy the code

Here we use the third method, which can be executed after writing the script:

npm run build
Copy the code

It will compile successfully.

Register the command

To develop the Nodejs command line tool, you provide a command that can be invoked directly, rather than executing the file as follows:

node lib/index.js
Copy the code

The effect we want is to execute a command that calls our JS file.

Create file bin/node-cli-demo in the current folder:

mkdir bin && touch bin/node-cli-demo.js
Copy the code

Then write the following to the file:

#! /usr/bin/env node
require('.. /lib/index.js');
Copy the code

The command for NPM package registration needs to be declared in package.json. Add the following:

{"name": "typescript-cli", "version": "0.0.1",+ "bin": {
+ "node-cli-demo": "./bin/node-cli-demo.js"
+},
}
Copy the code

This means executing our./bin/node-cli-demo.js file when executing node-cli-demo.

Finally, NPM link is called in the current directory, which puts our locally registered commands in the bin folder of the Nodejs installation directory. The system adds this folder to the path found by the command when Nodejs is installed. So we can just use the command we just registered:

node-cli-demo
// Your cli is running.
Copy the code

Automatically listens for file changes

We want to see the latest results every time we change the.ts file without having to manually execute NPM run build. We can use typescript’s –watch option to add the start command to the script in package.json:

{
    "script": {
+ "start": "tsc --watch"}}Copy the code

Run the command in the current directory:

npm start
Copy the code

Then make some changes to the SRC /index.ts file, open another console window and run Node-cli-demo to see that the printed content has been updated. This way, we only have to worry about coding while developing, not compiling.

Now we can write our code in the SRC file!

Note: The demo code for this article can be viewed on Github. To avoid creating many repositories, I put it in a subdirectory of the repository.

conclusion

The process for developing the Nodejs command line with TypeScript is as follows:

  1. Install typescript and configure it;
  2. inpackage.jsonTo declare the command and use itnpm linkLink it to a global command;
  3. usetsc --watchAutomatically listens for file changes and recompiles;
  4. Run the registered command to view the result.

This is all about building a TypeScript development environment for the Nodejs command line. I hope you can follow me and I will continue to write more excellent blogs to share with you. Meanwhile, if you have any questions, welcome to discuss ~

This post was first posted on my blog