2017-12-22 19 views
0

私はいくつかのコマンドを持っており、それらはすべて同じオプションを使用しています。例えばcommander.jsを使用して他のコマンドで定義されたオプションを再利用できますか?

..

program.command('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... 
    }); 

program.command('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... 
    }); 

私はこれをリファクタリングし、一度オプションを定義したいと思います。ただし、各コマンドで実行されるアクションは異なる場合があります。

オプションを一度宣言し、定義された/ allコマンドで使用する方法はありますか?

答えて

0

私が思いついた解決策は、同じ正確なオプションを持つコマンドでしか機能しません。独自のオプションを使用するには、おそらく私が見つけたソリューションを拡張するか、別の方法があるかもしれません。このソリューションは、私のために働いた:)

[ 
    { 
     name: 'hello', 
     method: 'hiMethod' 
    }, 
    { 
     name: 'world', 
     method: 'woMethod', 
    }, 
].forEach(cmd => { 
    program.command(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 
     }); 
}); 

:私が思いついた何

関連する問題