一、创建一个命令模块
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 noderequire('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 -hUsage: hello [options]

命令:

artisan morning good morning

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

示例:

hello -n tom say hello to TomCopyright 2019.