1. Let’s start with onehello world

Add it in package.json

{
  "bin": {
    "hellocli": "./index.js"}}Copy the code

This declares that the command is called hellocli and the entry file is index.js.

What if we want to use a global command like vue create hello-world?

usenpm install . -g ornpm linkTo register commands as global commands.index.jswrites

#! /usr/bin/env node
console.log('hello myCLI')
Copy the code

Be sure to write#! /usr/bin/env nodeOtherwise it won’t work. Now let’s test the command and run it on the terminalhellocli

2. Use the COMMAND line interface

2.1 Install NPM I commander -s first

Commander: The complete Node.js command-line solution. See the documentation for more

Add it to index.js

/** * capture command line input arguments */
program
    .command("create <name>")
    .action((res) = >{
      console.log(res)
    })

program.parse(process.argv);
Copy the code

Explanation:

  1. Command is declaring a command, so you can use hellocli create;


  2. is the name variable entered by the user;

  3. Program.parse (process.argv) is used to parse command-line input arguments;

  4. Action can get

    , which is printed

2.2 installationnpm i inquirer -S

Inquirer: A collection of generic command-line user interfaces for interacting with users. More Reference Documents

Add it to index.js

const inquirer = require('inquirer');
let list = [
  {
    type: 'list'.name: 'single'.message: 'Choose one'.choices: [
      'apple'.'banana'.'orange',]}, {type: 'checkbox'.message: 'alternative'.name: 'multiple'.choices: [{name: 'running'}, {name: 'Lift dumbbells'}, {name:"Push ups"
      }]
  }
]
program
    .command("create <name>")
    .action(async(res)=>{
      let listRes = await inquirer.prompt(list);
      console.log(listRes)
      console.log(res)
    })
Copy the code

Description:

  1. typeThe optional values are INPUT, number, confirm, list, rawList, expand, checkbox, password, and Editor
  2. nameWhat is defined here will show up in the result as shown below
  3. messageAre the clues
  4. choicesIs an array of options
  5. See the documentation for more

The renderings are as follows: Final printAt this point, we can go throughcommanderObtain the parameters output by the userinquirerGets the user selected option. Others can be based onnodeSome of the syntax for processing these fetched parameters in the.

You can refer to the CLI I wrote