您可以使用commander.js重用其他命令中定义的选项吗?
所以我有几个命令,他们都使用相同的选项。
例如..
programmand('hello')
.option('--foo <name>', 'this is the foo option and requires a name')
.option('--bar', 'this is the bar option and takes no arguments')
.action(options => {
// do stuff here...
});
programmand('world')
.option('--foo <name>', 'this is the foo option and requires a name')
.option('--bar', 'this is the bar option and takes no arguments')
.action(options => {
// do stuff here...
});
我想重构一下并定义一次选项。但是,对每个命令采取的操作可能不同。
有没有办法声明一次选项并将它们用于定义的任何/所有命令?
回答如下:我提出的解决方案仅适用于具有相同选项的命令。要使用独特的选项,您可能必须扩展我找到的解决方案,或者也许还有其他方法。
我想出了什么:
[
{
name: 'hello',
method: 'hiMethod'
},
{
name: 'world',
method: 'woMethod',
},
].forEach(cmd => {
programmand(cmd.name)
.option('--foo <name>', 'this is the foo option and requires a name')
.option('--bar', 'this is the bar option and takes no arguments')
.action(options => {
// do stuff here...
// I can use `cmd.method` for unique actions for each command
});
});
这个解决方案对我有用:)