start

I recently looked at the vue/ CLI source code, learned a lot of related core tool libraries, and planned to publish a series of core knowledge articles.

This is the first scaffolding series, after the periodic update (manual dog head), first dig a pit.

Familiarize yourself with a few tools before reading the source code or implementing one yourself. This article starts with the command line tool Commander!

commander

Commander is a lightweight, expressive and powerful command line framework that provides users with powerful command line input and parameter parsing functions.

This tool returns corresponding messages when you enter corresponding commands, such as vue-cli. After you install cli tools globally in the system, corresponding interactive information will pop up after you enter corresponding commands in the command prompt box, as shown in the screenshot below:

use

The version used for this tutorial is 6.2.0

Official Address:Github.com/tj/commande…

First installation

npm i commander
Copy the code

Introducing global objects

const { program } = require('commander');
Copy the code

The official tutorial also has a way of introducing Command to instantiate program objects

const { Command } = require('commander');
const program = new Command();
Copy the code

Note: To print the relevant information on the console after executing the relevant command, the following code must be executed at the end.

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

Version () method

This method can be used to output the current version number of your scaffolding tool.

parameter

  • The version number must be a parameter
  • This parameter is optional. The default value is-Vor--version
  • This parameter is optional
// Only version information program.version('1.0.0'); program.prase(process.argv); Program.version ('1.0.0', '-v, --vers'); program.prase(process.argv);Copy the code

The options () method

Commander uses the option() method to define options and can append a brief description of the options. Each option can define a short name of the option (- followed by a single character) and a long option name (-) followed by one or more words, use commas, Spaces, or | off.

parameter

  • This parameter is mandatory
    • A long a fault identification, use commas, Spaces, or | space
    • Identifiers can be followed by parameters,<>Is the required parameter,[]Is an optional parameter, for example-t --test <type>
  • Option description, optional parameter, this you use-hor--helpParameters are displayed
  • The default value of the option is optional

Basic usage

Options can be obtained from the Commander object property of the same name. For long options with multiple words, use the hump method. For example, –template-engine is associated with the program.templateengine property. For example, the –debug-test argument for the code shown below

Program.version ('1.1.0').option('-t, --test', 'test option function'). Option ('-d, --debug-test', 'test option function -- debug test'); // Note that to print the relevant information on the console after executing the relevant command, the following code must be executed at the end. program.parse(process.argv); console.log('----------------'); if(program.test) { console.log('you use --test commander'); } if(program.debugTest) { console.log('you use --debug-test commander'); } console.log('----------------');Copy the code

When you execute the corresponding file, such as node xxx.js -t or node xxx.js –test, you use –test commander will be printed. Js -d or node xxx.js –debug-test will output you use –debug-test commander.

With parameters and plus default values

You can follow the command with arguments, declared with <>

Program.version ('1.1.0'). Option ('-a, --argu-test <name>', 'test option function -- agru test') To print the relevant information on the console after executing the relevant command, you must execute the following code at the end. program.parse(process.argv); console.log('----------------'); if(program.arguTest) { console.log(`output: ${program.arguTest}`); } console.log('----------------');Copy the code

Js –argu-test=hello or node xxx.js -a hello outputs output: hello

Error: option ‘-a, –argu-test

‘ argument missing ‘error: option ‘-a, –argu-test

‘ argument missing’

We can also pass in a default value for the third argument to the option option in the code above, as follows:

option('-a, --argu-test <name>', 'test option function -- agru test', 'default value')
Copy the code

In this case, we execute the code directly, without any commands or arguments, and execute Node xxx.js to output output: default value.

Take the command

Precede your command with –no for the opposite of the command that follows.

Parse (process.argv); program.option('--no-opposite', 'test --no options'); if(program.opposite) { console.log('this is a word'); } else { console.log('this is a other word'); }Copy the code

In the code above, we execute this part of the code without any arguments. By default, program.opposite is true. This is a word. If we execute with the argument –no-opposite, we print this is an other word.

For more explanations, please refer to: github.com/tj/commande…

Custom options (functions)

Option () this method can also be followed by the custom function and the initial value after the option description, such as option(command, description, custom function, the initial or default value of the parameters of the custom function).

The function takes two arguments: a newly entered argument by the user and an existing argument.

function increaseFunc(value, preValue) {
  return preValue + 2;
}

program.option('-a, --add', 'add function', increaseFunc, 100);

program.parse(process.argv);

if(program.add > 100) {
  console.log(`current value: ${program.add}`)
}
Copy the code

Js -a, output 102, execute node xxx.js -a, output 104.

Variable-length argument

slightly

Address: github.com/tj/commande…

requiredOption()

The setting option is mandatory, and its argument is written the same as option(). For example

program
  .requiredOption('-a, --add <type>', 'add type must have be selected');
  
program.parse(process.argv);
Copy the code

In the above code, you must pass in the corresponding type argument when executing, otherwise the command will report an error.

command()

Commands can be configured using command(), such as create add on the Vue CLI. These commands are handled by command().

parameter

  • Configure the command name and parameters, command(‘ command name < Mandatory parameter > [Optional parameter]’), for example:command('create <name> [options]').
  • Configuration options, optional. Configure noHelp and isDefault. When opts. NoHelp is set to true, this command is not printed in the help message. When opts. IsDefault is set to true, this command is executed by default if no other subcommand is specified. Such as:command('create <name> [options]', { noHelp: true, isDefault: true }).

Declare variable parameters

Add… to the parameter name. To declare mutable arguments, and only the last argument supports this usage.

// Declare mutable arguments, which are passed to the handler as an array. program.command('start <name> [options...] ') .action((name, options) => { console.log(name); console.log(options); })Copy the code

Nodexxx.js start test Argumrnt

test
[ 'argument' ]
Copy the code

Nodexxx.js start test Argumrnt 1 2 3

test
[ 'argument', '1', '2', '3' ]
Copy the code

description()

The prompt, declarative statements used to describe the command, which we print when using the help command

parameter

  • Description statements, such as:description('create a proj').

action()

Custom callback function after command execution.

parameter

  • For example, if your command does not define optional and mandatory parameters, the first argument to the callback function is the Commander object. Otherwise, the last argument to the callback function is the Commander object. For example:
program.command('start') .description('start a commander') .action((cmd) => { console.log(cmd); // Output commander object information}) program.parse(process.argv);Copy the code

Execute the above code node xxx.js start and console the commander object.

program.command('start <name>') .description('start a commander') .action((name, cmd) => { console.log(name); // Output name console.log(CMD); // Output commander object information}) program.parse(process.argv);Copy the code
program.command('start <name> [options]') .description('start a commander') .action((name, options, cmd) => { console.log(name); // Output name console.log(options); // Output name console.log(CMD); // Output commander object information}) program.parse(process.argv);Copy the code

arguments()

Arguments can be used to specify arguments for the top-level command. The following code:

Arguments ('< CMD > [env]').description('test command').action(function(cmdValue, arguments).function (' cmdValue, ').arguments('< CMD > [env]').description('test command'). envValue) { console.log('command:', cmdValue); console.log('environment:', envValue || 'no environment given'); }); program.parse(process.argv);Copy the code

Nodexx.js start dev command: start environment: Nodexx. js build production command: build environment: production Arguments can be interpreted as a statement to match global commands.

other

The official documentation also includes some other knowledge, such as independent executable (sub) commands, custom help, custom event listening, etc., which is not described here. If you need to know more, please go to the official documentation: github.com/tj/commande…

The last

After learning from the previous command, you can write a complete command to operate

const { program } = require('commander'); The program version (1.0.0, '-v - vers). The command (' start < name > / options... ') .description('Test a whole commander order') .option('-e --extra [exargs]', 'Test a options') .action((name, // console.log(name, startOptions, CMD) => {// If your optional arguments are empty, then the output of this place is empty array. if(cmd.extra) { console.log(`cmd.extra's value is ${ cmd.extra }`); } else { console.log('no cmd.extra'); } if(startOptions.length > 0) { startOptions.forEach(function(item) { console.log(item); }) } }) program.parse(process.argv);Copy the code

This code I named commander-final.js. Then execute the following command:

  • node commander-final.js -vers
1.0.0
Copy the code
  • node commander-final.js -h
Usage: commander-final [options] [command] Options: -v, --vers output the version number -h, --help display help for command Commands: start [options] <name> [options...]  Test a whole commander order help [command] display help for commandCopy the code
  • node commander-final.js start -h
Usage: commander-final start [options] <name> [options...]  Test a whole commander order Options: -e --extra [exargs] Test a options -h, --help display help for commandCopy the code
  • node commander-final.js start mycli dev producrion -e hash
cmd.extra's value is hash
dev
producrion
Copy the code

The above is the corresponding command output learning.

If you have any mistakes or omissions, please give us more advice! Also welcome everyone to pay attention to my public number: program cookies!