前端架构: 脚手架框架之yargs高级应用教程

脚手架框架之yargs高级应用


1 )高级应用概述

  • 现在还用 xyzcli 这个脚手架,继续在这个项目中来看yargs的高级用法
  • 在 yargs 文档中, 给出了复杂应用的方式,这里做下详解
    • https://www.npmjs.com/package/yargs?activeTab=readme#complex-example
  • 这里主要关注 ↓
    • command
    • recommendCommands
    • fail

2 )command 应用案例

2.1 官方示例

  • 复杂应用案例,自定义 command
    #!/usr/bin/env node
    const yargs = require('yargs/yargs')
    const { hideBin } = require('yargs/helpers')yargs(hideBin(process.argv))// 注意 command的 四个参数.command('serve [port]', 'start the server', (yargs) => {return yargs.positional('port', {describe: 'port to bind on',default: 5000})}, (argv) => {if (argv.verbose) console.info(`start server on :${argv.port}`)serve(argv.port)}).option('verbose', {alias: 'v',type: 'boolean',description: 'Run with verbose logging'}).parse()
    
    • 这里 command 的四个参数分别是
      • 1 )command + options, 这里 serve [port]
        • 这里的serve是自定义的命令,如: $ xyzcli serve
        • 这里的 [port] 是 option,如: $ xyzcli serve --port
      • 2 )描述,这里是 start the server
        • 用于对前面命令和配置的补充描述
      • 3 )builder函数,这里是一个回调
        • builder是指在运行command之前做的一些事情
        • 这里会传入 yargs 对象
        • 比如在这里可以定义在这个 serve 命令中用到的 option
        • 这里定义了一个port参数,并给它一个5000的默认值
      • 4 )handler函数,用于具体执行 command 的行为
        • 比如这个 serve 命令启动了一个http的服务
        • 这个http服务就在这个 handler 函数中定义

2.2 在xyzcli中配置, 这里接上文走一个全量的代码

#!/usr/bin/env nodeconst yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');
const dedent = require('dedent');const arg = hideBin(process.argv);
const cli = yargs(arg)cli.usage('Usage: xyzcli [command] <options>').demandCommand(1, 'A command is required. Pass --help to see all available commands and options.').strict().alias('h', 'help').alias('v', 'version')// .alias('d', 'debug').wrap(cli.terminalWidth()).epilogue(dedent`Welcome to use xyzcli command line.We hope you guys work happily every day!For more information, please visit: https://xxx.com/xxx/xyzcli`).options({debug: {type: 'boolean',describe: 'Bootstrap debug mode',alias: 'd' // 这里添加了,上面就可以忽略了,推荐写在这里}}).option('registry', {type: 'string',describe: 'Define global registry',alias: 'r',// hidden: true, // 这个就不会出现在提示中,但是可以作为开发调试使用 --ci}).group(['debug'], '开发选项:').group(['registry'], '其他选项:').command('init [name]', 'Init your project', (yargs) => {yargs.option('name', {type: 'string',describe: 'Name of a project',alias: 'n',})}, (argv) => {console.log(argv);}).argv;
  • 执行 $ xyzcli init,查看输出
    { _: [ 'init' ], '$0': 'xyzcli' }
    
  • 执行 $ xyzcli init --name xx,查看输出
    { _: [ 'init' ], name: 'xx', '$0': 'xyzcli' }
    
  • 执行 $ xyzcli init -h,查看输出
    xyzcli init [name]Init your project开发选项:-d, --debug  Bootstrap debug mode                                                              [布尔]其他选项:-r, --registry  Define global registry                                                       [字符串]选项:-n, --name     Name of a project                                                             [字符串]-h, --help     显示帮助信息                                                                    [布尔]-v, --version  显示版本号                                                                      [布尔]
    
    • 可见最上面出现一则帮助提示
      xyzcli init [name]Init your project
      
  • 执行 xyzcli init -d -r npm -n x-project, 查看输出
    {_: [ 'init' ], // _ 里面就是注册的 command 命令// d 和 debug 存在这两个option, 则为trued: true,debug: true,// r 和 registry 也同样r: 'npm',registry: 'npm',// n 是 name,项目名称为 x-projectn: 'x-project',name: 'x-project',// $0 就是脚手架命令'$0': 'xyzcli'
    }
    
    • 注意,这种定义下,注意 alias 别名不能重复
    • 如果重复,覆盖了,就会出问题

2.3 参考 lerna 工程示例

  • 参考:https://github.com/lerna/lerna/blob/main/packages/lerna/src/index.ts
    // Bundled
    import { lernaCLI } from "@lerna/core";
    import changedCmd from "@lerna/commands/changed/command";
    import cleanCmd from "@lerna/commands/clean/command";
    import diffCmd from "@lerna/commands/diff/command";
    import execCmd from "@lerna/commands/exec/command";
    import importCmd from "@lerna/commands/import/command";
    import infoCmd from "@lerna/commands/info/command";
    import initCmd from "@lerna/commands/init/command";
    import listCmd from "@lerna/commands/list/command";
    import publishCmd from "@lerna/commands/publish/command";
    import runCmd from "@lerna/commands/run/command";
    import versionCmd from "@lerna/commands/version/command";import addCachingCmd from "./commands/add-caching/command";
    import repairCmd from "./commands/repair/command";
    import watchCmd from "./commands/watch/command";// Evaluated at runtime to grab the current lerna version
    const pkg = require("../package.json");module.exports = function main(argv: NodeJS.Process["argv"]) {const context = {lernaVersion: pkg.version,};const cli = lernaCLI().command(addCachingCmd).command(changedCmd).command(cleanCmd).command(createCmd).command(diffCmd).command(execCmd).command(importCmd).command(infoCmd).command(initCmd).command(listCmd).command(publishCmd).command(repairCmd).command(runCmd).command(watchCmd).command(versionCmd);applyLegacyPackageManagementCommands(cli);return cli.parse(argv, context);
    };
    
  • 按照上述这种用法,找其中一条 .command(listCmd)
  • 定位到 import listCmd from "@lerna/commands/list/command";
    • https://github.com/lerna/lerna/blob/main/packages/lerna/src/commands/list/command.ts 发现内容很少
  • 再次查看全局配置: https://github.com/lerna/lerna/blob/main/tsconfig.base.json
    "@lerna/commands/list": ["libs/commands/list/src/index.ts"],
    
  • 定位到这里 https://github.com/lerna/lerna/blob/main/libs/commands/list/src/command.ts
    import { filterOptions, listableOptions } from "@lerna/core";
    import type { CommandModule } from "yargs";/*** @see https://github.com/yargs/yargs/blob/master/docs/advanced.md#providing-a-command-module*/
    const command: CommandModule = {command: "list",aliases: ["ls", "la", "ll"],describe: "List local packages",builder(yargs) {listableOptions(yargs);return filterOptions(yargs);},async handler(argv) {return (await import(".")).factory(argv);},
    };export = command;
    
    • 可见这个 command 是一个对象,对象里有4项参数
  • 以上这个,是 Lerna 对yargs的内部应用,同样,在自己的脚手架中试验一下
    const cli = yargs(arg)cli.usage('Usage: xyzcli [command] <options>').demandCommand(1, 'A command is required. Pass --help to see all available commands and options.').strict().alias('h', 'help').alias('v', 'version')// .alias('d', 'debug').wrap(cli.terminalWidth()).epilogue(dedent`Welcome to use xyzcli command line.We hope you guys work happily every day!For more information, please visit: https://xxx.com/xxx/xyzcli`).options({debug: {type: 'boolean',describe: 'Bootstrap debug mode',alias: 'd' // 这里添加了,上面就可以忽略了,推荐写在这里}}).option('registry', {type: 'string',describe: 'Define global registry',alias: 'r',// hidden: true, // 这个就不会出现在提示中,但是可以作为开发调试使用 --ci}).group(['debug'], '开发选项:').group(['registry'], '其他选项:').command('init [name]', 'Init your 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 package',builder: (yargs) => {},handler: (argv) => { console.log(argv); }}).argv;
    
  • 执行 $ xyzcli list, 查看输出
    { _: [ 'list' ], '$0': 'xyzcli' }
    
  • 执行 $ xyzcli ls, 查看输出
    { _: [ 'ls' ], '$0': 'xyzcli' }
    
  • 执行 $ xyzcli ll, 查看输出
    { _: [ 'll' ], '$0': 'xyzcli' }
    
  • 执行 $ xyzcli la, 查看输出
    { _: [ 'la' ], '$0': 'xyzcli' }
    
  • 以上就是 command 的两种用法

3 )recommendCommands 应用案例

const cli = yargs(arg)cli.usage('Usage: xyzcli [command] <options>').demandCommand(1, 'A command is required. Pass --help to see all available commands and options.').strict().recommendCommands() // 注意这里.alias('h', 'help').alias('v', 'version')// .alias('d', 'debug').wrap(cli.terminalWidth()).epilogue(dedent`Welcome to use xyzcli command line.We hope you guys work happily every day!For more information, please visit: https://xxx.com/xxx/xyzcli`).options({debug: {type: 'boolean',describe: 'Bootstrap debug mode',alias: 'd' // 这里添加了,上面就可以忽略了,推荐写在这里}}).option('registry', {type: 'string',describe: 'Define global registry',alias: 'r',// hidden: true, // 这个就不会出现在提示中,但是可以作为开发调试使用 --ci}).group(['debug'], '开发选项:').group(['registry'], '其他选项:').command('init [name]', 'Init your 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 package',builder: (yargs) => {},handler: (argv) => { console.log(argv); }}).argv;
  • 上面加上 .recommendCommands() 之后, 尝试执行 $ xyzcli l, 查看输出
    Usage: xyzcli [command] <options>命令:xyzcli init [name]  Init your projectxyzcli list         List local package                                             [aliases: ls, la, ll]开发选项:-d, --debug  Bootstrap debug mode                                                                 [布尔]其他选项:-r, --registry  Define global registry                                                          [字符串]选项:-h, --help     显示帮助信息                                                                       [布尔]-v, --version  显示版本号                                                                         [布尔]Welcome to use xyzcli command line.
    We hope you guys work happily every day!For more information, please visit: https://xxx.com/xxx/xyzcli是指 ls?
    
    • 看这最后,是指 ls?, 这个命令就是当你输入不全时,尝试对你进行提醒

4 )fail 应用案例


cli.usage('Usage: xyzcli [command] <options>').demandCommand(1, 'A command is required. Pass --help to see all available commands and options.').strict().recommendCommands()// 注意这里.fail((msg, err) => {console.log('msg: ', msg)console.log('err: ', err)}).alias('h', 'help').alias('v', 'version')// .alias('d', 'debug').wrap(cli.terminalWidth()).epilogue(dedent`Welcome to use xyzcli command line.We hope you guys work happily every day!For more information, please visit: https://xxx.com/xxx/xyzcli`).options({debug: {type: 'boolean',describe: 'Bootstrap debug mode',alias: 'd' // 这里添加了,上面就可以忽略了,推荐写在这里}}).option('registry', {type: 'string',describe: 'Define global registry',alias: 'r',// hidden: true, // 这个就不会出现在提示中,但是可以作为开发调试使用 --ci}).group(['debug'], '开发选项:').group(['registry'], '其他选项:').command('init [name]', 'Init your 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 package',builder: (yargs) => {},handler: (argv) => { console.log(argv); }}).argv;
  • 尝试执行 $ xyzcli lxx 故意给一个没有的命令,查看输出结果

    msg:  是指 ls?
    err:  undefined
    msg:  无法识别的选项:lxx
    err:  undefined
    
    • 这里输出了 2个 msg, 两个 err, 这里 err 都是 undefined
    • 在实际应用中,参考 lerna, 如下
  • 参考 lerna 中的应用 https://github.com/lerna/lerna/blob/main/libs/core/src/lib/cli.ts#L18

    .fail((msg, err: any) => {// certain yargs validations throw strings :Pconst actual = err || new Error(msg);// ValidationErrors are already logged, as are package errorsif (actual.name !== "ValidationError" && !actual.pkg) {// the recommendCommands() message is too terseif (/Did you mean/.test(actual.message)) {// TODO: refactor to address type issues// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-ignorelog.error("lerna", `Unknown command "${cli.parsed.argv._[0]}"`);}log.error("lerna", actual.message);}// exit non-zero so the CLI can be usefully chainedcli.exit(actual.exitCode > 0 ? actual.exitCode : 1, actual);
    })
    

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/689912.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

19.Swift属性

Swift 属性 在 Swift 中&#xff0c;属性是类、结构体和枚举中的特征&#xff0c;用于存储值或提供计算值。Swift 中的属性可以分为存储属性&#xff08;Stored Properties&#xff09;和计算属性&#xff08;Computed Properties&#xff09;两种类型。 存储属性&#xff08…

莱卡云怎么样?简单测评下莱卡云韩国CN2云服务器

莱卡云服务器厂商&#xff0c;国内持证企业服务器商家&#xff0c;运作着香港、美国、韩国、镇江、日本、绍兴、枣庄、等数据中心的云服务器、独立服务器出租、设备托管、CDN等业务。今天为大家带来的是莱卡云韩国CN2服务器的详细评测&#xff0c;该云服务器的数据中心位于韩国…

外汇天眼:Monex计划重新任命八位现任董事,并任命三位新董事

Monex Group, Inc. 今日宣布&#xff0c;公司的提名委员会已决定在2024年6月举行的第20届股东年度大会上提议任命多位候选人加入董事会。 尽管公司认为现任董事熟悉其业务&#xff0c;因此目前尚不是替换他们的时机&#xff0c;但鉴于运营环境的显著变化和管理决策日益困难&…

显微测量|共聚焦显微镜大倾角超清纳米三维显微成像

用于材料科学领域的共聚焦显微镜&#xff0c;基于光学共轭共焦原理&#xff0c;其超高的空间分辨率和三维成像能力&#xff0c;提供了全新的视角和解决方案。 工作原理 共聚焦显微镜通过在样品的焦点处聚焦激光束&#xff0c;在样品表面进行快速点扫描并逐层获取不同高度处清…

Linux、Ubuntu、CenterOS、RedHat、Debian、AIpine关系和区别?

目录 1. 区别和联系 2. 安装命令 3. 其他发行版本 4.参考 1. 区别和联系 Ubuntu, Debian, RedHat, CentOS都是不同的Linux发行版。 Ubuntu 是基于Debian的一个开源GNU/Linux操作系统。它的目标是为一般用户提供一个最新同时又相当稳定&#xff0c;主要以自由软件建构而成…

与时共进,芯芯向荣丨纷享销客获时创意“最佳合作伙伴”表彰

近日&#xff0c;时创意存储产业园封顶仪式暨成立十五周年庆典在深圳圆满举行。本次盛典以“创意有时 芯芯向RONG”为主题&#xff0c;时创意董事长倪黄忠携全体员工&#xff0c;与政府嘉宾、产业伙伴等1200余人济济一堂&#xff0c;纷享销客也共襄盛举&#xff0c;并荣获【20…

C语言——oj刷题——找单身狗1

进阶版&#xff1a;找单身狗2https://blog.csdn.net/2301_80220607/article/details/136143380?spm1001.2014.3001.5501 题目&#xff1a; 在一个整型数组中&#xff0c;只有一个数字出现一次&#xff0c;其他数组都是成对出现的&#xff0c;请找出那个只出现一次的数字。 例…

element 表单提交图片(表单上传图片)

文章目录 使用场景页面效果前端代码 使用场景 vue2 element 表单提交图片   1.点击【上传图片】按钮择本地图片&#xff08;只能选择一张图片&#xff09;后。   2.点击图片&#xff0c;支持放大查看。   3.点击【保存】按钮&#xff0c;提交表单。 页面效果 前端代码…

【Jvm】运行时数据区域(Runtime Data Area)原理及应用场景

文章目录 前言&#xff1a;Jvm 整体组成 一.JDK的内存区域变迁Java8虚拟机启动参数 二.堆0.堆的概念1.堆的内存分区2.堆与GC2.1.堆的分代结构2.2.堆的分代GC2.3.堆的GC案例2.4.堆垃圾回收方式 3.什么是内存泄露4.堆栈的区别5.堆、方法区 和 栈的关系 三.虚拟机栈0.虚拟机栈概念…

TrustGeo框架代码构成

该存储库提供了TrustGeo框架的原始PyTorch实现。 一、基础用法 1、需求 Requirements 代码使用python 3.8.13、PyTorch 1.12.1、cudatoolkit 11.6.0和cudnn 7.6.5进行了测试。通过Anaconda安装依赖: # create virtual environment conda create --name TrustGeo python=3.8.…

【C++之语法篇002】

C学习笔记---002 C知识语法篇1、缺省参数1.1、什么是缺省参数?1.2、缺省参数分类1.3、缺省参数的总结 2、函数重载2.1、什么是函数重载?2.2、C支持函数重载?2.3、那么对于函数重载&#xff0c;函数名相同该如何处理?2.4、那么C是如何支持重载&#xff1f; 3、引用3.1、什么…

QGis软件 —— 3、QGis创建形状图层点、通过xlsx及csv加载点

(方式一 ) 通过QGis创建形状图层点 1、如下gif&#xff0c;演示了创建形状图层 2、如下gif&#xff0c;演示了在高德地图上&#xff0c;形状图层上添加点 3、如下gif&#xff0c;演示了对形状图层点查看详细信息 4、如下gif&#xff0c;演示了对形状图层点查看属性表&#xff0…

生成式 AI - Diffusion 模型的数学原理(2)

来自 论文《 Denoising Diffusion Probabilistic Model》&#xff08;DDPM&#xff09; 论文链接&#xff1a; https://arxiv.org/abs/2006.11239 Hung-yi Lee 课件整理 文章目录 一、基本概念二、VAE与Diffusion model三、算法解释四、训练过程五、推理过程 一、基本概念 Diff…

代码随想录算法训练营第15天—二叉树04 | ● *110.平衡二叉树 ● *257. 二叉树的所有路径 ● 404.左叶子之和

*110.平衡二叉树 题目链接/文章讲解/视频讲解&#xff1a;https://programmercarl.com/0110.%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.html 考点 后序遍历二叉树高度计算 我的思路 错误地将平衡二叉树的定义等价为判断整体二叉树的最大深度和最小深度之差是否大于1 视…

Redis系列学习文章分享---第一篇(Redis快速入门之初始Redis--NoSql+安装redis+客户端+常用命令)

目录 今天开始进入Redis系列学习分享1.初识Redis1.1.认识NoSQL1.1.1.结构化与非结构化1.1.2.关联和非关联1.1.3.查询方式1.1.4.事务1.1.5.总结 1.2.认识Redis1.3.安装Redis1.3.1.依赖库1.3.2.上传安装包并解压1.3.3.启动1.3.4.默认启动1.3.5.指定配置启动1.3.6.开机自启 1.4.Re…

【MySQL】变量、流程控制

一、变量 在MySQL的存储过程与函数中&#xff0c;可以使用变量来存储查询或计算的中间结果数据&#xff0c;或者输出最终的结果数据。它可以分为用户自定义变量与系统变量 1、系统变量 1&#xff09;系统变量分为全局变量&#xff08;需要使用关键字global&#xff09;和会话…

JS 深克隆和浅克隆 浅析

深克隆&#xff08;Deep Clone&#xff09;和浅克隆&#xff08;Shallow Clone&#xff09;是在复制对象或数组时常用的两种概念。它们主要区别在于复制的深 深克隆&#xff08;Deep Clone&#xff09;&#xff1a; 深克隆是指完全复制一个对象或数组&#xff0c;包括对象或数…

【前端素材】bootstrap5实现房产信息网HomeFi平台(附源码)

一、需求分析 房产信息网是一个在线平台,专门提供房地产相关信息的网站。这些网站通常为买家、卖家、租客、房地产经纪人等提供各种房产信息,包括可售房屋、出租房源、房价走势、地产市场分析、房产投资建议等内容。以下是房产信息网的主要功能和特点: 房源信息浏览:用户可…

Failed to load resource: net::ERR_FILE_NOT_FOUND问题解决

publicPath是告诉 webpack 打包后的文件在浏览器中的访问路径。当你设置 publicPath: ./ 时&#xff0c;实际上是将构建后的资源相对于当前路径进行引用。 相对路径引用&#xff1a; 默认情况下&#xff0c;Vue CLI 生成的项目会把所有静态资源引用路径设置为绝对路径&#xff…

【lesson60】网络基础

文章目录 网络发展认识协议网络协议初识OSI七层模型TCP/IP五层(或四层)模型网络传输基本流程数据包封装和分用网络中的地址管理 网络发展 以前没有网络剧的工作模式是&#xff1a;独立模式:&#xff0c;计算机之间相互独立 所以多个计算机要协同开发比较难。 有了网络以后&am…