yargs工作流程

3 minute read

yargs 脚手架开发框架

脚手架构成

bin:package.json中配置bin,npm link本地安装 command:命令 options:参数 文件顶部增加 #!/usr/bin/env node

脚手架初始化流程

构造函数yargs()以及常用方法 脚手架参数解析方法:hideBin(process.argv)/Yargs.parse(argv, optoins) 命令注册方法yargs.command()/yargs.command({})

yargs初体验

#!/usr/bin/env node

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

//hideBin 用于解析参数
const arg = hideBin(process.argv)

// yargs的使用
yargs(arg).argv;

得出的结果是:

➜  core git:(master) ✗ i18n-fe --help
选项:
  --help     显示帮助信息           [布尔]
  --version  显示版本号             [布尔]
完善脚手架帮助文档
const cli = yargs(arg);

cli
.strict() // 严格模式,若是出现不匹配的参数,会出现错误提示
.usage('Usage:i18n-fe [command] <options>')
.demandCommand(1, "A command is required. Pass --help to see all available commands and options.")
// demandCommand(至少要输入n个command,提示文案)
.alias('h', 'help')
.alias('v', 'version')
.wrap(cli.terminalWidth())// 命令框的宽度 .wrap(100)
.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/suibu/i18n-fe
`) //反标号可根据我们书写的格式,直接显示。dedent可让文案全部顶格展示
.options({
  debug: {
    type: 'boolean',
    describe: '启动debug模式',
    alias: 'd'
  }
})
.option('registry', { type: 'boolean', describe: '定义全局地址' })
// 分组功能
.group(['debug'], 'group name')
.argv;

效果如下:

➜  i18n-fe git:(master) ✗ i18n-fe
Usage:i18n-fe [command] <options>

调试功能
  -d, --debug  启动debug模式                                                         [布尔]

选项:
  -r, --registry  定义全局地址                                                       [布尔]
  -h, --help      显示帮助信息                                                       [布尔]
  -v, --version   显示版本号                                                         [布尔]

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/suibu/i18n-fe

A command is required. Pass --help to see all available commands and options.
➜  i18n-fe git:(master) ✗
借鉴lerna的帮助文档处配置代码
const os = require("os");

module.exports.globalOptions = globalOptions;

function globalOptions(yargs) {
  // the global options applicable to _every_ command
  const opts = {
    loglevel: {
      defaultDescription: "info",
      describe: "What level of logs to report.",
      type: "string",
    },
    sort: {
      // proxy for --no-sort
      hidden: true,
      type: "boolean",
    },
    "max-buffer": {
      describe: "Set max-buffer (in bytes) for subcommand execution",
      type: "number",
      requiresArg: true,
    },
  };

  // group options under "Global Options:" header
  const globalKeys = Object.keys(opts).concat(["help", "version"]);

  return yargs.options(opts).group(globalKeys, "Global Options:").option("ci", {
    hidden: true,
    type: "boolean",
  });
}

完善脚手架command注册
cli
.strict() // 严格模式,若是出现不匹配的参数,会出现错误提示
.usage('Usage:i18n-fe [command] <options>')
.demandCommand(1, "A command is required. Pass --help to see all available commands and options.")
// demandCommand(至少要输入n个command,提示文案)
.alias('h', 'help')
.alias('v', 'version')
.alias('d', 'debug')
// 命令框的宽度 .wrap(100)
.wrap(cli.terminalWidth())
.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/suibu/i18n-fe
`) //反标号可根据我们书写的格式,直接显示。dedent可让文案全部顶格展示
.options({
  debug: {
    type: 'boolean',
    describe: '启动debug模式',
    alias: 'd'
  }
})
.option('registry', { type: 'string', describe: '定义全局地址', alias: 'r' })
// 分组功能
.group(['debug'], '调试功能')
.group(['registry'], '附加功能')
.command('init [name]', 'do init a project', (yargs) => {
  yargs.option('name', { type: 'string', describe: 'name of a project', alias: 'n' })
}, (argv) => {
  console.log(argv)
})
.argv;

来检验一下输出

➜  i18n-fe git:(master) ✗ i18n-fe init suibu -r taobao -d
{
  _: [ 'init' ],
  r: 'taobao',
  registry: 'taobao',
  d: true,
  debug: true,
  '$0': 'i18n-fe',
  name: 'suibu',
  n: 'suibu'
}

你会发现 别名和全称都出现了;-r taobao :代表registry的值是taobao;init suibu: 命令init,name 是suibu

学习lerna的command注册

function main(argv) {
  const context = {
    lernaVersion: pkg.version,
  };

  return cli()
    .command(addCmd)
    .command(bootstrapCmd)
    .command(changedCmd)
    .command(cleanCmd)
    .command(createCmd)
    .command(diffCmd)
    .command(execCmd)
    .command(importCmd)
    .command(infoCmd)
    .command(initCmd)
    .command(linkCmd)
    .command(listCmd)
    .command(publishCmd)
    .command(runCmd)
    .command(versionCmd)
    .parse(argv, context);
}

// 进入listCmd
exports.command = "list";

exports.aliases = ["ls", "la", "ll"];

exports.describe = "List local packages";

exports.builder = (yargs) => {
  listable.options(yargs);

  return filterOptions(yargs);
};

exports.handler = function handler(argv) {
  return require(".")(argv);
};

本质上暴露了一个对象
推荐命令、错误信息配置

提供很多帮助信息

cli
.recommendCommands()
.fail((msg, err) => {
  // 可对输入错误,暴露出个性化定制
  console.log(err)
})
.argv;

完整版
#!/usr/bin/env node

const yargs = require('yargs/yargs')
const dedent = require('dedent')
// const { hideBin } = require('yargs/helpers')
const pkg = require('../package.json')

//hideBin 用于解析参数
// const arg = hideBin(process.argv)

const argv = process.argv.slice(2)
const context = { version: pkg.version  }
const cli = yargs(argv, context);

cli
.strict() // 严格模式,若是出现不匹配的参数,会出现错误提示
.usage('Usage:i18n-fe [command] <options>')
.demandCommand(1, "A command is required. Pass --help to see all available commands and options.")
// demandCommand(至少要输入n个command,提示文案)
.alias('h', 'help')
.alias('v', 'version')
.alias('d', 'debug')
// 命令框的宽度 .wrap(100)
.wrap(cli.terminalWidth())
.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/suibu/i18n-fe
`) //反标号可根据我们书写的格式,直接显示。dedent可让文案全部顶格展示
.options({
  debug: {
    type: 'boolean',
    describe: '启动debug模式',
    alias: 'd'
  }
})
.option('registry', { type: 'string', describe: '定义全局地址', alias: 'r' })
// 分组功能
.group(['debug'], '调试功能')
.group(['registry'], '附加功能')
.command('init [name]', 'do init a project', (yargs) => {
  yargs.option('name', { type: 'string', describe: 'name of a project', alias: 'n' })
}, (argv) => {
  console.log(argv)
})
.recommendCommands()
.fail((msg, err) => {
});
SuiBu

SuiBu

Engineer

Comments

  Write a comment ...