前端技术之命令模块及其执行方法

26次阅读

共计 1332 个字符,预计需要花费 4 分钟才能阅读完成。

一、创建一个命令模块
1、package.json

{
  "name": "@uad/nat-cli",
  "version": "0.0.2",
  "description": "Demo",
  "main": "index.js",
  "bin": {"artisan": "./src/artisan.js"},
  "scripts": {"test": "echo \"Error: no test specified\"&& exit 1"},
  "repository": {"type": "git"},
  "keywords": ["CLI"],
  "author": "chunrong.liu",
  "license": "ISC",
  "dependencies": {
    "shelljs": "^0.8.3",
    "yargs": "^13.2.4"
  }
}

2、src/artisan.js

#!/usr/bin/env node
require('shelljs/global');
var argv = require('yargs')
.option('n', {
alias : 'name',
demand: true,
default: 'tom',
describe: 'your name',
type: 'string'
})
.usage('Usage: hello [options]')
.example('hello -n tom', 'say hello to Tom')
.help('h')
.alias('h', 'help')
.epilog('Copyright 2019')
.command("morning", "good morning", function (yargs) {echo("Good Morning");
var argv = yargs.reset()
.option("m", {
alias: "message",
description: "provide any sentence"
})
.help("h")
.alias("h", "help")
.argv;
echo(argv.m);
})
.argv;
console.log('hello', argv.n);
console.log(argv._);

二、使用方法
1、将命令模块通过 npm link 进行全局注册后,即可在命令行窗口直接使用该命令
2、在其它模块中的 package.json 中引用命令模块,并增加 scripts

"scripts": {"artisan": "artisan"},
"dependencies": {
  ......
  "@uad/nat-cli": "^0.0.2",
  ......
}

增加对命令模块的依赖后,执行 npm install 后,会在 node_modules/.bin 目录下生成命令的快捷方式,在 scripts 中即可使用。
命令执行方法如下:

npm run artisan -- -h

npx artisan -h

Usage: hello [options]

命令:

  artisan morning  good morning

选项:
–version 显示版本号 [布尔]
-n, –name your name [字符串] [必需] [默认值: “tom”]
-h, –help 显示帮助信息 [布尔]

示例:

hello -n tom  say hello to Tom

Copyright 2019.

正文完
 0