First, create a command module
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._);
Second, the use
After 1, the command module globally registered by npm link, can use this command in command window
2, reference command module package.json in other modules, and increasing the scripts
"scripts": { "artisan": "artisan" }, "dependencies": { ...... "@uad/nat-cli": "^0.0.2", ...... }
After increasing dependence on the command module, after performing npm install, shortcuts to commands generated at node_modules / .bin directory, can be used in scripts.
Command as follows:
npm run artisan -- -h
or
npx artisan -h Usage: hello [options]
command:
artisan morning good morning
Options:
--version Show the version number [Istanbul]
-n, --name your name [String] [required] [Default: "tom"]
-h, --help display help information [Istanbul]
Example:
hello -n tom say hello to Tom
Copyright 2019.