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 link
To register commands as global commands. 在index.js
writes
#! /usr/bin/env node
console.log('hello myCLI')
Copy the code
Be sure to write#! /usr/bin/env node
Otherwise 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:
Command is declaring a command, so you can use hellocli create;
is the name variable entered by the user;
Program.parse (process.argv) is used to parse command-line input arguments;
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:
type
The optional values are INPUT, number, confirm, list, rawList, expand, checkbox, password, and Editorname
What is defined here will show up in the result as shown belowmessage
Are the clueschoices
Is an array of options- See the documentation for more
The renderings are as follows: Final printAt this point, we can go throughcommander
Obtain the parameters output by the userinquirer
Gets the user selected option. Others can be based onnode
Some of the syntax for processing these fetched parameters in the.
You can refer to the CLI I wrote