Skip to content
Go back

yargs常用方法

Published:  at  05:45 PM

yargs是一个命令行参数解析器,它可以帮助你快速构建一个命令行工具。


const yargs = require('yargs/yargs')
// 页脚格式化插件
const dedent = require('dedent')
const pkg = require('../package.json')

const cli = yargs()
const argv = process.argv.slice(2)

const context = {
    cliVersion: pkg.version
}

cli
    .usage('Usage:lio-imooc-test [command] <options>')
    .demandCommand(1, 'A command is required. Pass --help to see all available commands and options.最少要输入一个参数')// 最少要输入一个参数
    .strict()
    .recommendCommands()
    .fail((err, msg) => {
        console.log('err =======>', err)
        console.log('msg =======>', msg)
    })
    .alias('h', 'help')
    .alias('v', 'version')
    .wrap(cli.terminalWidth())// 显示的宽度(撑满全屏)
    .epilogue(dedent`  hello 
        world`)// 去除缩进
    .options({// 对所有的command添加的options都有效
        debug: {// 添加debug命令
            type: 'boolean',
            describe: 'Bootstrap debug mode',
            alias: 'd'
        }
    })
    .option('ci', {
        type: 'string',
        describe: 'Define global registry',
        alias: 'r'
    })
    .group(['debug'], 'Dev Options:')// 把debug添加到Dev Options中
    .group(['registry'], 'Extra Options:')
    .command('init [name]', 'Do init a project', (yargs) => {
        yargs
            .option('name', {
                type: 'string',
                describe: 'Name of a project',
                alias: 'n'
            })
    }, (argv) => {
        console.log(argv)
    })
    .command({
        command: 'list',
        aliases: ['ls', 'la', 'll'],
        describe: 'List local packages',
        builder: (yargs) => {

        },
        handler: (argv) => { }
    })
    .parse(argv, context)// 将默认参数与配置参数合并


Previous Post
Commander常见用法
Next Post
lerna用法及其构建命令详解