Command-line tools are often used in front-end development, such as @babel/cli, vue-cli, creation-react-app, etc. So how do you create an NPM command-line tool? It’s actually very simple, just a few steps.

create

1 Initialize the NPM project

NPM init Package Name: (cli) gogocode- CLI version: (1.0.0) Description: my-first-CLI entry point: (index.js) Keywords: npm cli author: super manCopy the code

2 Configure the bin field

Json file. Add a bin field to the file. The key of the bin field is your command (gogocode) and the value points to the path relative to package.json (index.js). Different keys correspond to different commands. Refer to the documentation for more information about the bin field.

{
  "name": "gogocode-cli"."version": "1.0.0"."description": "my-first-cli"."bin": {
    "gogocode": "index.js"}}Copy the code

3 Create the index.js file

Create the index.js file in the project root directory. Here is the contents of the index.js file: Use the console.log() function to output the command line return information.

 #!/usr/bin/env node
 console.log('Hello, world! ');
Copy the code

Note: The first line must add a script specifying the runtime environment (#! The/usr/bin/env node)

4 Packaged Release

4.1 release

  • Execute the NPM pulish command in the project root directory. Follow the prompts to publish your command-line tools to the NPMJS platform. You need to register an NPM account during this period.
npm publish
Copy the code
  • Once packaged, you can see your NPM package on the NPMJS website.

4.2 validation

  1. Install the NPM package globally
npm install gogocode-cli -g
Copy the code
  1. Execute the command
gogocode
Copy the code
  1. Correctly output “Hello, World!” 😊

Advancements & tools

The NPM command line tool is just a quick run-through from preparation to release, and there are some auxiliary development kits that are needed to build complex NPM command line applications. The following two NPM packages are commonly used: Commander and terminal-kit

Commander

  • Commander is used to organize command line commands and options. It is responsible for processing input information on the command line.

    • Command is used to define a code logic. This generally refers to the text between the first space and the second space in the command line tool. For example: NPM init, where init is a command. A single command line tool can support multiple command inputs.
    • Option can be understood as a function entry to an instruction. Start with a hyphen (-) or a hyphen (–), for example, ls -a, where -a is a parameter that lists all files. Note: “-” is a short form of “–“.
  • The following uses gogocode-CLI, a command line tool recently developed by us, as an example to explain how to use Commander in detail.

    • First let’s look at the code of the entry file index.js:
#! /usr/bin/env node
const program = require('commander');
const term = require('terminal-kit').terminal;
const pkg = require('./package.json');
// Plugin load and execute logic
const transform = require('./transform');
// Initialize the plug-in project logic
const init = require('./commands/init');

/ / configuration command
program
.command(`init`)
.description('Initialize a plug-in sample project')
.action((options) = > {
    init(options);
});

/ / configuration options
program.option('-t, --transform <package name or path>'.'Plug-in path or NPM package name, multiple plug-ins supported, comma separated')
.option('-o, --out <path>'.'Output file path')
.option('-s, --src <path>'.'Source file path to convert')
.action((options) = > {
    return transform(options);
});

// Configure CLI information, version, and CLI description
program
.version(pkg.version)
.description(term.blue('GoGoCode code conversion has never been easier https://gogocode.io'));
console.log();

// take over command line input, parameter processing
program.parse(process.argv);
Copy the code
  • Gogocode -CLI external support init command and -t,-o,-s and other parameters (options) definition, specific definition as follows:
Parameter | instruction abbreviations Parameters that type
init init Initialize a plug-in sample project command
–src -s Path to the source file to be converted option
–transform=FILE/npm package -t Plug-in path or NPM package name option
–out -o Output file path option
  • Let’s execute index.js:
node ./index.js
Copy the code

The results are as follows:

We can see that COMMANDER automatically helps us deal with the command and parameter display and logical separation problems, and automatically adds -v and -h options. Very convenient, so to speak.

terminal-kit

Terminal-kit is a powerful command line output tool that supports various interactive forms such as text style, table, menu, and progress bar. Here are a few common functions.

  1. Font color, output blue text
const term = require('terminal-kit').terminal;
term.blue('GoGoCode code conversion has never been easier https://gogocode.io');
Copy the code
  1. Table output
const term = require('terminal-kit').terminal;
term.table([
    ['header #1'.'header #2'.'header #3'],
    ['row #1'.'a much bigger cell, a much bigger cell, a much bigger cell... '.'cell']] and {hasBorder: false.contentHasMarkup: true.textAttr: { bgColor: 'default' },
    firstCellTextAttr: { bgColor: 'blue' },
    firstRowTextAttr: { bgColor: 'yellow' },
    firstColumnTextAttr: { bgColor: 'red' },
    checkerEvenCellTextAttr: { bgColor: 'gray' },
    width: 60.fit: true   // Activate all expand/shrink + wordWrap});Copy the code
  1. Yes or No
const term = require('terminal-kit').terminal;

term('Do you like gogocode? [Y|n]\n');

term.yesOrNo({ yes: ['y'.'ENTER'].no: ['n']},function (error, result) {

    if (result) {
        term.green("'Yes' detected! Good bye! \n");
        process.exit();
    }
    else {
        term.red("'No' detected, are you sure? \n"); }});Copy the code

debugging

How to Debug command line tools? We can do this.

  1. Switch vscode (latest version) built-in terminal (terminal) to JavaScript Debug terminal
  2. Break points using vscode’s built-in breakpoint feature.
  3. Run the node./index.js command in JavaScript Debug Terminal to Debug


gogocode

The above NPM command line development experience is summarized in the development of Gogocode – CLI process. Gogocode – CLI is gogoCode’s command-line tool. So what is gogocode? To quote the official introduction:

GoGoCode is a tool to manipulate AST. It can lower the threshold of using AST and help developers to focus on the development of code analysis transformation logic. Simple replacements don't even need to learn the AST, and more complex analysis transformations can be done once you have learned the AST node structure (see THE AST viewer).Copy the code

IO/en /docs/ SPE… Gogocode is a quick, easy-to-use code-conversion tool.

Gogocode conversion plug-in

Since GogoCode works so well, how do we write conversion plug-ins using GogoCode? The following for everyone to explain it:

Plug-in initialization

  • First you need to install Gogocode – CLI
npm install gogocode-cli -g
Copy the code
  • Then execute “Gogocode Init” to initialize a plug-in project
gogocode init
Copy the code

Plug-in project structure

Gogocode init is a standard NPM project. The main entry for the project is configured in the package.json main node.

As can be seen from the screenshot above, the plug-in project transformation logic entry is transform.js, which is defined as follows:

/** * convert entry to export a function, as follows function signature *@param {*} FileInfo contains source and Path attributes. Source is the text to be converted, and path is the path *@param {*} The API includes Gogocode as a conversion tool *@param {*} Options * is passed to other options@returns {string} Returns the converted code */
module.exports = function(fileInfo, api, options) {
  const sourceCode = fileInfo.source;
  const $ = api.gogocode;
  return $(sourceCode)
    .replace('const a = $_$'.'const a = 2')
    .generate();
};
Copy the code

Our transformation logic needs to be defined in the above function

Transformation logic execution

Gogocode – CLI executes js files

The conversion logic can be executed as a JS file. Here are the commands:

gogocode -s ./test/input.vue -t ./transform.js -o out.vue
Copy the code

For details about the gogocode-cli command parameters, see the gogocode-cli parameter definitions in the commander chapter.

Gogocode – CLI executes the NPM package

If you want to share your plugin, you can package the project as an NPM package. Gogocode – CLI also supports the ability to run NPM transformation logic. For example, we released a “vue2-to-3” NPM plug-in. You can execute the following command to run the transformation logic in the NPM package.

gogocode -s ./test/input.vue -t ./vue2-to-3 -o out.vue
Copy the code

GoGoCode related links

Github repository for GoGoCode (new project begged star ^_^) github.com/thx/gogocod…

GoGoCode’s official website gogocode. IO /

Play. Gogocode. IO /

Ali mom out of the new tool, to batch modify the project code to alleviate the pain of “GoGoCode actual battle” learn 30 AST code replacement tips 0 cost start AST, with GoGoCode to solve Vue2 Vue3 problem GoGoCode to help clean up the code in the “garbage”