This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

background

At present, most of the common Node.js CLI tools used in front-end development are actually written by JS shuttle:

  • yarn
  • @vue/cli
  • create-react-app
  • nrm
  • webpack
  • @babel/cli
  • .

With TS, there is very little:

  • vsce
  • cac
  • caporal
  • ?????

So I built a TS based node.js CLI scaffolding to give writing node.js CLI an option.

benefits

So what are the benefits of using TS to write node. js CLI? I think there are three points:

Enjoy the development experience of TS

In the development process, you can enjoy the benefits of TS syntax declaration hints, type verification and so on, and have a better development experience. In the following figure, when we call a defined method, we can clearly see the parameters and parameter types of the called method:

We also throw a specific error if we pass an argument that doesn’t match the function’s requirements:

And after packaging, each source code ending in.ts is packaged into a.d.ts file, which is the syntax declaration file automatically generated by TS. In most cases, you can use ~ directly

For more information about how to use TS, visit the OFFICIAL website of TS

Better compatibility

The packaged JS code is the ES2015 version of JS packaged into the source code, which is compatible with lower versions of Node.js. The pre-package code looks like this:

export const exec = (cmd: string, options = {}): Promise<any> = > {return new Promise((resolve, reject) = > {
    const stdout = shell.exec(cmd, options, (error: number | null, stdout: string, stderr: string) = > {
      if (error) {
        reject(error)
      }
      resolve({ error, stdout, stderr })
    })
    stdout.on('exit'.(code: number | null, signal: NodeJS.Signals | null) = > {
      resolve({ code, signal })
    })
  })
}
Copy the code

After the package:

var exec = function (cmd, options) {
    if (options === void 0) { options = {}; }
    return new Promise(function (resolve, reject) {
        var stdout = shell.exec(cmd, options, function (error, stdout, stderr) {
            if (error) {
                reject(error);
            }
            resolve({ error: error, stdout: stdout, stderr: stderr });
        });
        stdout.on('exit'.function (code, signal) {
            resolve({ code: code, signal: signal });
        });
    });
};
exports.exec = exec;
Copy the code

Use new grammar sugar

You can use extension operators, class classes, async/await, and other new JS syntax sugars in your development:

class A {
  b () {
    return 1}}console.log([1.2.3. [1.2.3]])
Copy the code

As for the compatibility problem of the new grammar sugar, TS has already solved it for us after packing. The above class and extension operators, when packaged, look like this:

var A = (function () {
    function A() {
    }
    A.prototype.b = function () {
        return 1;
    };
    returnA; } ());console.log(__spreadArray([1.2.3], [1.2.3].false));
Copy the code

disadvantages

Of course, using TS to write node.js CLI brings some disadvantages:

  • The compiled code is less readable and relatively cumbersome to debug
  • There is a learning cost to learn how to use TS

For this cost, if you want to study TS, it’s not a disadvantage.

Usage scenarios

So, should YOU use TS for Node.js CLI development?

If you have the following two scenarios:

  • Want to taste new, want to learn TS
  • The CLI tool needs to provide apis

Then I recommend you try ~

Matters needing attention

What do I need to know about using TS to develop the Node.js CLI if I want to try it out?

Some NPM packages require manual import of syntax declaration files

If you introduce a package that doesn’t display syntax prompts when calling its methods, it probably doesn’t come with a TS declaration file. You can search for @types packages in the official TS types package search portal, for example here I searched for Lodash:

In fact, most of the subtypes declaration files can be found in @types

The import package mode is changed

With TS, many NPM packages do not provide modular exports, so you need to change the import mode of such packages to this:

import * as chalk from 'chalk'
import * as ora from 'ora'
import * as shell from 'shelljs'

// ...
Copy the code

Don’t distribute with the source code

This can be done by setting the files field in package.json:

{
  "files": [
    "/bin"."/lib"]}Copy the code

Try not to write any

A big reason to use TS is for friendly syntax hints and strict type declarations,

If you write too much “any”, then it’s meaningless to use “TS”,

It’s like a rou jia mo without meat…

Common Node.js CLI NPM package is recommended

  • Commander: Used for command configuration and parameter parsing. Similar options include Caporal, YARgs, CAC, and Optionator
  • Chalk: Log output with multiple colors
  • Dotenv: Used for environment variable resolution
  • Http-server: used to start the static HTTP server
  • Inquirer: Used for command-line interaction
  • Lodash: the famous JS tool library, the package is very large, recommended on demand import
  • Update-notifier: indicates that the CLI tool automatically updates information
  • Download-git-repo: Used to download code from Github, often used when creating scaffolding by command
  • shelljs: used to invoke system commands, for examplecd,cp,ls,rmEtc, compatible with Windows and Linux
  • Ora: used to create Loading effects, equivalent to the Loading component in the React component

More Node.js CLI NPM packages are recommended

Create scaffolding using Wy-CLI

After reviewing the pros and cons and considerations above, if you want to try something new or learn about TS, or if you need to write an API for Node.js CLI, try my scaffolding, global installation:

npm i @wytxer/wy-cli -g
Copy the code

Then execute wy init project-name to install the scaffold and select the command line scaffold from the list:

❯ Command line scaffolding (Node.js + TypeScript + Commander)Copy the code

Scaffolding common commands:

# installation
yarn install

# Start development
yarn dev

# packaged
yarn build

# release
npm publish
Copy the code

Code and documentation

Thank you for reading, scaffolding will be long-term maintenance, welcome to download and use: scaffolding GitHub address

Scaffolding usage documentation is also kept up to date.

If you have a problem with using it, please feel free to submit an issue