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] <options>')
    .strict()
    .argv

使用--help將會打印出使用信息

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

選項:
  --help     顯示幫助信息                                                 [布爾]
  --version  顯示版本號  

最少輸入的command個數: demandCommand

yargs(arg)
    .usage('Usage: test [command] <options>')
    .demandCommand(1, '最少輸入一個參數')
    .strict()
    .argv

設置command別名: alias

yargs(arg)
    .usage('Usage: test [command] <options>')
    .demandCommand(1, '最少輸入一個參數')
    .strict()
    .alias('h', 'help') //-h 和  --help 效果一樣
    .argv

設置輸出內容的寬度: wrap

const cli = yargs(arg)
cli.usage('Usage: test [command] <options>')
    .demandCommand(1, '最少輸入一個參數')
    .strict()
    .alias('h', 'help')
    .wrap(cli.terminalWidth()) // terminalWidth返回當前窗口的寬度
    .argv

設置結尾顯示的內容: epilogue

cli.usage('Usage: test [command] <options>')
    .demandCommand(1, '最少輸入一個參數')
    .strict()
    .alias('h', 'help')
    .wrap(cli.terminalWidth())
    .epilogue('結尾顯示的話')
    .argv

為全局command添加選項: options

cli.usage('Usage: test [command] <options>')
    .alias('h', 'help')
    .options({
        debug: { // 添加的選項名
            type: 'boolean',
            describe: 'debug mode',
            alias: 'd'  // 別名
        }
    })
    .argv
// options('name', {}) 一個一個設置的用法

執行效果

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

選項:
      --version  顯示版本號                                               [布爾]
  -d, --debug    debug mode                                              [布爾]
  -h, --help     顯示幫助信息                                             [布爾]

將選項分組: group

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

執行效果

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

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] <options>')
    .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' }
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容