@noresources /命令
一个轻量级的命令行接口定义包,专注于可重用性、可扩展性和干净的API。
安装
npm install --save @noresources/command
功能
- 基于普通对象的命令组件描述符
- 程序
- 命令,子命令
- 选项
- 位置
- 参数(选项和位置参数值类型)
- 基于链的程序构建器API
- 导出到众所周知的命令包
示例
组件描述符
命令、选项和位置参数可以使用一个简单的javascript对象来声明。
export const Verbosity = {
'type': 'counter',
'documentation': 'Verbosity level',
'initial': 0,
'names': ['verbosity', 'v']
};
然后,工厂函数将创建正确的类实例。
import { createOption } from "@noresources/command"
const option = createOption(Verbosity);
构建器API
这个 ProgramBuilder 类提供了一个流畅的接口,以使用方法链定义整个程序接口。
import { ProgramBuilder } from "@noresources/command"
const builder = new ProgramBuilder;
builder.name('chatbot')
.version('1.2.3')
.option(Verbosity) // out option descriptor presented above.
.positional({
documentation: 'Some text to insert in conversation'
}).handler(function (input) {
if (input.options.verbosity > 2) console.log('Bark bark')
if (input.arguments.length)
console.log (input.arguments[0])
console.log ('This program is not really meaningful'),
})
导出到commander.js
目前,这个包本身不提供命令行解析器。它依赖于完善的解析器 Commander.js用于解析的to。
转换 @noresources/command 程序到a Commander.js 命令是通过一个简单的函数调用生成的。
import { createCommand } from '@noresources/command/commander'
const command = createCommand(builder.program); // assuming builder is the ProgramBuilder instance defined above.
command.parse ();
请注意 commander 包不包括在 @noresources/command 包依赖关系。您必须手动安装它才能使用此功能。