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

本文介绍了一个自定义CLI命令模块的创建过程,包括配置package.json,编写artisan.js脚本,使用yargs和shelljs库来解析命令行参数和执行操作。同时,详细说明了如何全局注册并使用此命令模块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、创建一个命令模块

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.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值