「工具链🔧」带你玩转黑框框的Yargs🏴‍☠️🏴‍☠️(Yargs包教会指南)

195 阅读2分钟

Hi,又见面了,这里还是JustHappy的技术博客,今天我们来玩一个很酷的开源项目——Yargs 🏴‍☠️🏴‍☠️🏴‍☠️

本文将借助Yargs带您实现一个简单的基于Node.js的命令行工具🔧🔧

我们来看看这个Yargs有多出名吧👨🏻‍💻

image.png

可以看到截止本文撰写,Yargs已经有两年多没有发布新的版本了,但是npm依旧保持在一亿多的下载量,足以见这个开源项目的优秀以及该项目在Node生态里面的地位了。很多知名的脚手架项目都使用了Yargs比如说Vue-CLI

image.png

What is “Yargs”?“fer hearties tryin'ter?⛵️

有关Yargs这个单词我特地去查了一下,这用的不多,其意思是代指海盗之间的黑话差不多的意思,想想咱写程序的,不就是应该有海盗那种勇敢的冒险精神,同时看到官网首页的Slogan中fer hearties tryin'ter —— 为真挚且努力的人,有些莫名的感动,谁说程序员不懂烂漫😭😭

OK,不废话,Yargs其实真的很简单,我们开始吧🚉

初始化项目 && 安装Yargs

npm init -y

npm install --save yargs

在根目录下创建一个index.js文件来编写我们的代码

为了偷懒我们可以直接把官网Getting Start的内容直接复制进来,我们就在这个基础上改进

以下是我加了注释的版本,大家也可以直接复制这个,也相信大家看完这段代码也就会怎么使用Yargs了,结合文档和ChatGPT,我想这是很容易的事情😄😄 点这里去文档

#!/usr/bin/env node

require('yargs')// 引入 yargs 模块
  .scriptName('pirate-parser') // 设置脚本的名称,这将在帮助help中显示
  .usage('$0 <cmd> [args]')// 设置脚本的使用说明,这将在帮助help中显示
  .command(
    'hello [name]',// 命令名称和参数
    'welcome ter yargs!',
    (yargs) => {  // 这个函数用于定义命令 'hello' 的选项
      yargs.positional('name', {
        type: 'string',// 参数类型为字符串
        default: 'Cambi',//如果没有提供 'name' 参数,则默认为 'Cambi'
        describe: 'the name to say hello to'// 参数描述
      })
    },
    function (argv) { // 这是命令 'hello' 的回调函数,当执行 'hello' 命令时会调用
      console.log('hello', argv.name, 'welcome to yargs!')
    }
  )
  .help().argv   // 启用帮助命令,'--help' 将显示帮助文档
  //argv解析命令行参数并执行相应的命令

我们来测试一下目前的吧!

# 先运行以下命令使得我们编辑的包建立链接
npm link

# 链接成功后我们就可以看看目前的命令是否ok,运行以下命令
node index.js --help

image.png

可以看到成功打印,我们继续用一下

image.png

开始编写我们自己的node命令行工具吧

一个来自我自己的需求:我需要查看电脑中的Git代理端口和修改Git代理端口,但是查看Git端口和配置Git端口的命令太长了,我每次改都要去查,所以我们来编写一个查改Git端口的小工具吧🚀🚀

以下是我写的index.js代码

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

const argv = yargs(hideBin(process.argv))
  .usage('Usage: $0 <command> [options]')
  .command('check', '查看本地的 git proxy 配置')
  .command(
    'set <proxy>',
    '设置 git proxy',
    (yargs) => {
      yargs.positional('proxy', {
        type: 'string',
        describe: 'the proxy URL to set'
      })
    },
    (argv) => {
      setGitProxy(argv.proxy)
    }
  )
  .demandCommand(1, 'You must provide a command')
  .help()
  .alias('help', 'h').argv

function checkGitProxy() {
  exec('git config --global --get http.proxy', (error, stdout, stderr) => {
    if (error) {
      console.error(`exec error: ${error}`)
      return
    }
    console.log('Git HTTP Proxy:', stdout.trim())
  })

  exec('git config --global --get https.proxy', (error, stdout, stderr) => {
    if (error) {
      console.error(`exec error: ${error}`)
      return
    }
    console.log('Git HTTPS Proxy:', stdout.trim())
  })
}

function setGitProxy(proxy) {
  exec(`git config --global http.proxy '${proxy}'`, (error, stdout, stderr) => {
    if (error) {
      console.error(`exec error: ${error}`)
      return
    }
    console.log('Git HTTP Proxy set to:', proxy)
  })

  exec(`git config --global https.proxy '${proxy}'`, (error, stdout, stderr) => {
    if (error) {
      console.error(`exec error: ${error}`)
      return
    }
    console.log('Git HTTPS Proxy set to:', proxy)
  })
}

switch (argv._[0]) {
  case 'check':
    checkGitProxy()
    break
  case 'set':
    // 'set' 命令的参数在 argv._[1] 中
    setGitProxy(argv._[1])
    break
  default:
    console.log('Unknown command')
    process.exit(1)
}

这是运行起来的样子

image.png

image.png

ok,到你啦,之后如果有机会我们还会基于这个打造一个属于我们自己的脚手架,当然,这需要你的支持!!!

最后:如果您喜欢,不妨帮小弟点个赞,文章有任何问题都可以评论区留言哦。 fer heaties tryin'ter为努力且真挚的人