npm command line tool development guide

We often use command-line tools in front-end development, such as @babel/cli,vue-cli,create-react-app wait. So how to create an npm command line tool? In fact, it's very simple. It only takes a few steps.

establish

1 initialize 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 man

2. Configure bin field

npm init generates a package JSON file, add a bin field in the file, the key of the bin field is your command (gogocode), and the value points to the relative package JSON path (index.js). Different keys correspond to different commands. For more information about the bin field, refer to file.

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

3. Create index JS file

Create index. In the project root directory JS file. Here is index JS file content: use console Log() function to output the information returned from the command line.

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

Note: in the first line, you must add a script to specify the running environment (#! / usr/bin/env node)

4 packaging and publishing

4.1 release

  • Execute the npm pulish command at the root of the project. Follow the system prompts to publish your command line tools to npmjs Platform. You need to register an npm account during this period. You can baidu by yourself.
npm publish

4.2 verification

  1. Global installation npm package
npm install gogocode-cli -g
  1. Execute command
gogocode
  1. Correctly output "Hello, World!" 😊

Advanced & Tools

The above just makes npm command line tools easy to run from preparation to release. If you need to build complex npm command line applications, you also need to use some auxiliary development packages. Here are two commonly used npm packages: commander and terminal-kit

Commander

  • commander is used to organize command line instructions and parameters. It is mainly responsible for processing the input information of the command line.

    • Command can be understood as "instruction", which is used to define a code logic. Generally refers to the text between the first space and the second space of the command-line tool. For example: npm init, where init is a command. A command line tool can support multiple instruction inputs.
    • option can be understood as the function input parameter of "instruction". Start with "-" or "–", for example: ls -a, where - A is a parameter, representing the listing of all files. Note: "-" is a short form of "–".
  • Here's a command line tool we recently developed gogocode-cli As an example, let's explain it in detail commander How to use.

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

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

// Configure options
program.option('-t, --transform <package name or path>', 'Plug in path or npm Package name,Multiple plug-ins are supported, separated by commas')
.option('-o, --out <path>', 'Output file path')
.option('-s, --src <path>', 'Source file path to be converted')
.action((options) => {
    return transform(options);
});

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

// Take over command line input and parameter processing
program.parse(process.argv);
  • We can see from the above code: gogocode-cli It supports the definition of init command and - t,-o,-s and other parameters (option s). The specific definitions are as follows:
Parameter instructionabbreviationParameter descriptiontype
initinitInitialize a plug-in sample projectcommand
–src-sSource file path to be convertedoption
–transform=FILE/npm package-tPlug in path or npm package nameoption
–out-oOutput file pathoption
  • Let's execute index js:
node ./index.js

The results are as follows:

We can see commander Automatically help us deal with the display of instructions and parameters and logical splitting, and automatically add - V and - h option s. It can be said that it is very convenient.

terminal-kit

terminal-kit It is a powerful command line output tool, which supports text style, table, menu, progress bar and other interactive forms. Here are some common functions.

  1. Font color, output blue text
const term = require('terminal-kit').terminal;
term.blue('GoGoCode  Transcoding has never been easier  https://gogocode.io');
  1. Table 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']
], {
    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
}
);
  1. Yes or No ask
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");
    }
});

debugging


How to Debug during the development of command line tools? We can do this.

  1. Switch the vscode (latest version) built-in terminal to JavaScript Debug Terminal
  2. Use the built-in breakpoint function of vscode to break points.
  3. Execute node in JavaScript Debug Terminal/ index. JS to debug


gogocode

The above npm command line development experience is a small series in development gogocode-cli From the process. gogocode-cli yes gogocode Command line tools. that gogocode What is it? To quote the official introduction:

GoGoCode Is an operation AST The use of tools can be reduced AST Threshold to help developers from cumbersome AST Liberate from operation and focus more on the development of code analysis and transformation logic. Simple replacement without even learning AST,And preliminary study AST Node structure (for reference) AST Viewer), you can complete more complex analysis transformation.

Official documents of gogocode gogocode.io/zh/docs/spe...


gogocode can be said to be a quick and cool code conversion tool.

gogocode conversion plug-in

Since gogocode is so easy to use, how can we use gogocode to write conversion plug-ins? Let's explain:

Plug in initialization

  • First, you need to install gocode cli
npm install gogocode-cli -g
  • Then execute "gogocode init" to initialize a plug-in project
gogocode init

Plug in project structure

The plug-in directory initialized by gogocode init is a standard npm project. The main entry of the project is configured in package The main node of JSON.

In the screenshot above, we can see that the transformation logic entry of the plug-in project is transform JS, specifically defined as follows:

/**
 * Export a function from the conversion entry, and sign the function as follows
 * @param {*} fileInfo Contains the source and path attributes. Source is the text to be converted and path is the path
 * @param {*} api Include gocode as a conversion tool
 * @param {*} options Other option s are passed in here
 * @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();
};


Our transformation logic needs to be defined in the above function

Conversion logic execution

Gogocode cli execute js file

The conversion logic can be executed in the form of js file. The following is the specific command:

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

Among them, gogocode-cli Refer to the above for the definition of command line parameters commander Parameter definition of gogocode cli in chapter.

Gogocode cli executes npm package


If you want to package the project into npm, you can share it directly.
Gogocode cli also supports the function of running npm transformation logic.
For example, we released an npm plug-in of "vue2-to-3". 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

Gocode related links

Github warehouse of GoGoCode (star)
https://github.com/thx/gogocode

Gocode's official website
https://gogocode.io/

You can come to playground to experience it quickly
https://play.gogocode.io/


Ali's mother's new tool alleviates the pain of batch modifying project codes
"GoGoCode practice" learn 30 AST code replacement tips in one breath
0 cost start AST, solve Vue2 and Vue3 migration problems with GoGoCode
Gocode helps clean up "garbage" in code

Keywords: Javascript npm shell

Added by cry of war on Fri, 18 Feb 2022 18:37:28 +0200