2017-12-22 2 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 
     }); 
}); 

이 솔루션은 나를 위해 일한 :)

관련 문제