如何使用 yargs

什么是 Yargs

Yargs

Yargs 是一个很好的命令行程序库,简单地说,它可让建立一个在控制台中运行的应用程序的过程变得垂手可得。还有什么能让它变得更好呢?它是以海盗为主题的(它的名字叫 YARgs),让它正式成为有史以来最好的工具。javascript

你可能知道其余的 CLI,好比 vue-cli,能够轻松设置一个 Vue.js 项目或 create-react-app,因此这个概念对大多数人来讲应该很熟悉。vue

开始

mkdir yargs_practice
cd yargs_practice
touch yargs.js
复制代码

初始化项目, 并安装 yargsjava

npm init -y
npm i yargs
复制代码

package.json 以下所示:node

{
  "name": "yargs_practice",
  "version": "1.0.0",
  "description": "",
  "main": "yargs.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "yargs": "^15.3.1"
  }
}
复制代码

使用 vscode 打开当前目录react

code .
复制代码

编辑 yargs.jsgit

const yargs = require("yargs");
const argv = yargs.argv;
console.log(argv);
复制代码

在终端中运行github

node yargs.js add --new thing --old="stuff"
复制代码

获得以下结果vue-cli

yargs

yard 能够很方便的拿到命令行参数npm

继续修改 yargs.jsjson

const yargs = require("yargs");
const argv = yargs
  .command("add", "Add a new note")
  .command("list", "List all notes")
  .help().argv;
复制代码
  • command 能够增长命令行信息
  • help 方法能够显示帮助信息

在终端中运行

node yargs.js --help
复制代码

显示以下信息

yargs

yargs 提供了快捷命令方法(alias)让一些命令更简洁

继续修改 yargs.js

const yargs = require("yargs");
const argv = yargs
  .command("add", "Add a new note")
  .command("list", "List all notes")
  .help()
  .alias("help", "h").argv;
复制代码

在终端中运行

node yargs.js -h
复制代码

会获得和--help 同样的结果

TODO:: option 没看明白

const yargs = require("yargs");
const argv = yargs
  .command("add", "Add a new note")
  .command("list", "List all notes")
  .help()
  .alias("help", "h").argv;
复制代码

option

yargs 还支持子命令 用法以下

const yargs = require("yargs");
const argv = yargs
  .command("add", "Add a new note", {
    title: {
      describe: "Title of note",
      alias: "t",
      demandOption: true,
    },
    body: {
      describe: "Body of note",
      alias: "b",
      demandOption: true,
    },
  })
  .command("list", "List all notes")
  .help()
  .option("find")
  .alias("help", "h").argv;
复制代码

add 这个命令增长了子命令 title

  • describe 是这条命令的描述
  • alias 是这条命令的简写
  • demandOption 表示 title 必须传递参数

当咱们在终端中执行

node yargs.js add -h
复制代码

yargs

注意这里有别于 node yargs.js -h 这里展现的是 add 这条命令的具体帮助信息

实例

咱们经过一个小的实例来看 yargs 如何使用

咱们须要对这个package.json文件作一些调整,由于咱们要建立一个 CLI。如今看起来应该是这样的。

{
  "name": "yargs_practice",
  "version": "1.0.0",
  "description": "",
  "main": "yargs.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "bin": {
    "line-count": "./line-count"
  },
  "keywords": ["cli"],
  "preferGlobal": true,
  "author": "",
  "license": "ISC",
  "dependencies": {
    "yargs": "^15.3.1"
  }
}
复制代码

如下是须要注意的重要改动。

咱们添加了一个 bin 值,它将咱们稍后建立的条目文件映射到它的可执行文件名上(你能够设置为任何你想要的名字 咱们已经将 preferGlobal 设置为 true,这意味着咱们的软件包但愿被全局安装(例如经过 npm install -g)。 其余的调整包括改变描述、删除已使用的脚本、添加做者名称等。

建立一个基本的 CLI

Yargs 让解析命令行参数变得很是简单,不少例子项目能够在这里找到。

咱们将建立一个基本的 CLI,它能够接收一个文件做为参数并计算它的行数。

要作到这一点,首先建立一个主脚本文件。

touch line-count
复制代码

编辑这个文件

#!/usr/bin/env node
const argv = require("yargs")
  .usage("Usage: $0 <command> [options]")
  .help("h")
  .alias("h", "help").argv;
复制代码

让咱们把全部的代码逐条逐句的说说。

  1. #!/usr/bin/env node 是一个 shebang 行的实例,它告诉咱们的系统用什么解释器来执行该文件
  2. .usage('Usage: $0 <command> [options]')设置当调用 --help 命令时将显示的 CLI 的用法信息。
  3. .help('h') 将帮助命令绑定到选项 h 上。
  4. .alias('h', 'help') 为选项 -h 建立了一个别名,即 --help

与你所见,这第一步是很是简单的,yargs 的语法很直观。

接下来咱们要添加count命令。

只需在你已有的 CLI 中添加如下几行。

.command("count", "Count the lines in a file")
.example("$0 count -f foo.js",
  "count the lines in the given file")
复制代码

逐行看看:

  1. .command("count", "count the lines in a file") 建立了一个新的命令,名称为 count,并设置了一个描述。

  2. .example("$0 count -f foo.js", "count the lines in the given file") 建立一个带有描述的例子,当用户调用 --help 选项或者当他们忘记这个命令时,它将显示出来。

这些都很好,但如今运行node line-count计数并无什么做用,接下来咱们须要一个文件名,经过计数并显示其行数来完成 CLI。

添加以下信息

.alias("f", "file")
.nargs("f", 1)
.describe("f", "Load a file")
.demandOption(["f"])
复制代码

line-count 最后应该是这样的样子。

#!/usr/bin/env node
const argv = require("yargs")
  .usage("Usage: $0 <command> [options]")
  .command("count", "Count the lines in a file")
  .example("$0 count -f foo.js", "count the lines in the given file")
  .alias("f", "file")
  .nargs("f", 1)
  .describe("f", "Load a file")
  .demandOption(["f"])
  .help("h")
  .alias("h", "help").argv;
复制代码

逐行,解释下新添加的代码

  1. .alias("f", "file") 为-f 选项建立别名 --file。

  2. .nargs("f", 1) 为该选项设置一个参数(文件名),不然显示 --help 菜单。

  3. .description("f", "Load a file")为该选项添加一个描述。

  4. .demandOption([["f"]),由于咱们须要一个文件名,因此咱们要求选项-f。

最后,让咱们把程序的逻辑加上。

// Create stream with the file
const s = fs.createReadStream(argv.file);

var lines = 0;
s.on("data", (buf) => {
  // Get the number of lines
  lines += buf.toString().match(/\n/g).length;
});

s.on("end", () => {
  // Display the number of lines
  console.log(lines);
});
复制代码

就这样,咱们来试试。

createReadStream

到如今为止,咱们的程序一直是这样运行的,但若是直接调用它,就会报错。

line-count

咱们能够经过使用 npm link 命令将二进制文件(咱们以前在 package.json 中定义为 bin)进行全局注册来解决这个问题。

在当前目录下执行

npm link
复制代码

恭喜 🎉,你如今能够像这样在本地运行你的脚本了。

line-count count -f package.json
复制代码

line-count

发布 CLI 到 NPM

在部署以前,咱们须要在 package.json 中添加一些信息。

"homepage": "YOUR GITHUB REPO OR SITE HERE",
"repository": {
  "type": "git",
  "url": "git+YOUR GITHUB REPOSITORY HERE"
},
"engines": {
  "node": ">=8"
},
复制代码
  • homepage 和 repository 要填写你本身的 GitHub 项目地址
  • engines 确认 nodejs 版本号,简单地定义了你的项目应该在最小版本的节点上工做。 版本号取决于你用了那些版本的特性。

下面是接下来的步骤。

  • npmjs.com 上建立一个帐户(可选,若是有能够忽略)
  • 运行 npm login 命令并输入你的信息
  • 运行 npm publish 命令,它将在几分钟内自动发布。

就是这样! 若是你想在未来更新你的项目,你须要在 package.json 文件中修改它的版本号,而后再次运行发布命令。

参考

  1. Building a CLI with Yargs
  2. How to use Yargs
相关文章
相关标签/搜索