2017-12-22 1 views
0

Also habe ich mehrere Befehle und sie alle verwenden die gleichen Optionen.Können Sie Optionen, die in anderen Befehlen definiert sind, mit commander.js wiederverwenden?

Zum Beispiel ..

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... 
    }); 

Ich möchte das Refactoring und die Optionen einmal definieren. Die für jeden Befehl ausgeführten Aktionen können jedoch abweichen.

Gibt es eine Möglichkeit, Optionen einmal zu deklarieren und sie für alle definierten Befehle zu verwenden?

Antwort

0

Die Lösung, die ich gefunden habe funktioniert nur für Befehle, die die gleichen Optionen haben. Um mit einzigartigen Optionen zu arbeiten, müssten Sie wahrscheinlich die gefundene Lösung erweitern, oder vielleicht gibt es auch noch einen anderen Weg.

Was ich kam mit:

[ 
    { 
     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 
     }); 
}); 

diese Lösung für mich gearbeitet :)

Verwandte Themen