yargs入门

Yargs通过解析参数来帮助您构建脚手架的工具。

通过yargs创建一个最简单的脚手架工具

定义文件index.js

#!/usr/bin/env node

const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')

const arg = hideBin(process.argv)
yargs(arg)
     .argv

执行

> ./index.js --help
选项:
  --help     显示帮助信息                                                 [布尔]
  --version  显示版本号                                                   [布尔]

严格模式: strict

yargs(arg)
    .strict()
    .argv

加入strict,如果有无法识别的参数,将会给出提示

用法提示: usage

yargs(arg)
    .usage('Usage: test [command] ')
    .strict()
    .argv

使用--help将会打印出使用信息

> ./index.js --help
test [command] 

选项:
  --help     显示帮助信息                                                 [布尔]
  --version  显示版本号  

最少输入的command个数: demandCommand

yargs(arg)
    .usage('Usage: test [command] ')
    .demandCommand(1, '最少输入一个参数')
    .strict()
    .argv

设置command别名: alias

yargs(arg)
    .usage('Usage: test [command] ')
    .demandCommand(1, '最少输入一个参数')
    .strict()
    .alias('h', 'help') //-h 和  --help 效果一样
    .argv

设置输出内容的宽度: wrap

const cli = yargs(arg)
cli.usage('Usage: test [command] ')
    .demandCommand(1, '最少输入一个参数')
    .strict()
    .alias('h', 'help')
    .wrap(cli.terminalWidth()) // terminalWidth返回当前窗口的宽度
    .argv

设置结尾显示的内容: epilogue

cli.usage('Usage: test [command] ')
    .demandCommand(1, '最少输入一个参数')
    .strict()
    .alias('h', 'help')
    .wrap(cli.terminalWidth())
    .epilogue('结尾显示的话')
    .argv

为全局command添加选项: options

cli.usage('Usage: test [command] ')
    .alias('h', 'help')
    .options({
        debug: { // 添加的选项名
            type: 'boolean',
            describe: 'debug mode',
            alias: 'd'  // 别名
        }
    })
    .argv
// options('name', {}) 一个一个设置的用法

执行效果

> ./index.js -h
Usage: test [command] 

选项:
      --version  显示版本号                                               [布尔]
  -d, --debug    debug mode                                              [布尔]
  -h, --help     显示帮助信息                                             [布尔]

将选项分组: group

cli.usage('Usage: test [command] ')
    .alias('h', 'help')
    .options({
        debug: {
            type: 'boolean',
            describe: 'debug mode',
            alias: 'd'
        }
    })
    .group(['debug'], 'Dev Options:')
    .argv

执行效果

> ./index.js -h
Usage: test [command] 

Dev Options:
  -d, --debug  debug mode                                                [布尔]

选项:
      --version  显示版本号                                               [布尔]
  -h, --help     显示帮助信息                                             [布尔]

命令纠错提示:recommendCommands()

会根据当前输入的command去找最相似的进行提示

自定义错误信息: fail((err,msg) => {...})

dedent库

去除每行顶部空格,方便多行字符串的输出

const dedent = require('dedent')
console.log(dedent`
    第一行,
    第二行
`)
// 将会订购显示输出
/**
第一行,
第二行
*/

自定义命令

官方示例

#!/usr/bin/env node
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')

yargs(hideBin(process.argv))
    .command(
        'serve [port]', // serve 脚手架后面输入的名,[port]定义的option
        'start the server', // 描述
        (yargs) => { //builder,在执行这个command之前做的事情
            yargs
                .positional('port', {
                    describe: 'port to bind on',
                    default: 5000
                })
        }, 
        (argv) => { // handler,执行comand 的行为
            if (argv.verbose) console.info(`start server on :${argv.port}`)
            serve(argv.port)
        }
    )
    .option('verbose', {
        alias: 'v',
        type: 'boolean',
        description: 'Run with verbose logging'
    })
    .argv

自定义

cli.usage('Usage: test [command] ')
    .alias('h', 'help')
    .options({
        debug: {
            type: 'boolean',
            describe: 'debug mode',
            alias: 'd'
        }
    })
    .group(['debug'], 'Dev Options:')
    .command('init [name]', '初始化的命令', (yargs) => {
        yargs.option('name', {
            type: 'string',
            describe: 'init的option',
            alias: 'n'
        })
    }, (argv) => {
        console.log(argv)
    })
    .argv

执行效果

> ./index.js init  
{ _: [ 'init' ], '$0': 'index.js' }

> ./index.js init -h 
ndex.js init [name]

初始化的命令

Dev Options:
  -d, --debug  debug mode                                                 [布尔]

选项:
      --version  显示版本号                                               [布尔]
  -n, --name     init的option                                           [字符串]
  -h, --help     显示帮助信息                                             [布尔]

使用对象方式定义

    ...
    .command({
        command: 'list',
        aliases: ['ls', 'la', 'll'],
        describe: 'list 的描述',
        builder: (yargs) => {

        },
        handler: (argv) => {
            console.log(argv)
        }
    })
    .argv
parse

解析命令参数,合并传入的参数,合并完作为一个新的参数注入到脚手架中

#!/usr/bin/env node

const yargs = require('yargs/yargs')
const pkg = require('../package.json')

const argv = process.argv.splice(2)
const context = {
    testVersion: pkg.version
}

yargs()
    .command({
        command: 'list',
        aliases: ['ls', 'la', 'll'],
        describe: 'list 的描述',
        builder: (yargs) => {},
        handler: (argv) => {
            console.log(argv)
        }
    })
    .parse(argv, context)

执行效果

> ./index.js list
{ _: [ 'list' ], testVersion: '1.0.5', '$0': 'index.js' }

你可能感兴趣的:(yargs入门)