脚手架工具——yargs的使用

本文详细介绍了如何使用yargs库来构建和配置Node.js命令行工具。内容包括命令行选项设置、别名、自定义错误处理、命令分组、命令参数解析以及帮助信息的定制。通过示例展示了初始化命令`init`和`list`的定义及处理函数,帮助开发者更好地理解和创建自己的CLI工具。
摘要由CSDN通过智能技术生成
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')
const dedent = require('dedent')
const pkg = require('../package.json')
const arg = hideBin(process.argv)
const cli = yargs(arg)
const argv = process.argv.slice(2)
const context = {
  ltVersion: pkg.version
}
cli
  // 用法说明
  .usage("usage:liushuran-test [command] <options>")
  // 期望最少输入1个命令
  .demandCommand(1, "A command is required. Pass --help to see all available commands and options.")
  // 输入错误时,会有近似命令提示
  .recommendCommands()
  // 自定义错误信息
  .fail((err, msg) => {
    console.log(err)
  })
  // 不能识别时,会有错误提示
  .strict()
  // 别名
  .alias("h", "help")
  .alias("v", "version")
  // .alias("d", "debug")
  // 修改输出内容宽度
  .wrap(cli.terminalWidth())
  // 页脚内容(dedent作用(可以使用es6模板字符串):去掉空格,顶行显示,空行不会去掉)
  .epilogue(dedent`
    When a command fails, all logs are written to lerna-debug.log in the current working directory.

    For more information, find our manual at https://github.com/lerna/lerna
  `)
  // 全局options设置,对所有command有效
  .options({
    debug: {
      type: "boolean",
      describe: "Boostrap debug mode",
      alias: "d" // options的别名推荐方式
    }
  })
  // 定义一个option
  .option("registry", {
    type: "string",
    describe: "Define global registry",
    alias: "r",
    // hidden: true // 命令会被隐藏,用于内部开发使用
  })
  // 对命令进行分组
  .group(["debug"], "Dev Options:")
  .group(["registry"], "Extra Options:")
  // command
  // 第一个参数command命令,[*]定义command后面的参数对应的是哪个option,command init 相当于 command init name
  // 第二个参数command描述
  // 第三个参数是builder(运行之前),定义option
  // 第四个参数是handler,具体执行
  .command("init [name]", "Init project", (yargs) => {
    // 不输入option时,默认执行的option
    yargs.positional("name", {
      describe: '默认name值',
      default: "myCommand"
    })
    // 定义command options
    yargs.option("name", {
      type: "string",
      describe: "init command option name",
      alias: "n"
    })
    yargs.option("test", {
      type: "string",
      describe: "init command option test",
      alias: "t"
    })
  }, (argv) => {
    console.log(argv)
  })
  // command 另一种写法
  .command({
    // command命令
    command: 'list',
    // command别名
    aliases: ['ls', 'la', 'll'],
    // command描述
    describe: 'List local packages',
    // builder(运行之前),定义option
    builder: (yargs) => {
    },
    // 具体执行
    handler: (argv) => {
      console.log(argv)
    }
  })
  // .argv;
  // 将argv和自定义对象合并之后注入
  .parse(argv, context)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值