2017-11-15 8 views
1

位置指定引数を正しく構成する方法が見つかりません。私はこのコードを持っている:Yargs - 省略された位置引数のカスタムエラーmsgの提供方法

#!/usr/bin/env node 

const create = (argv) => { 
    console.log('create component with name:', argv.name) 
} 

const createBuilder = (yargs) => { 
    yargs.positional('name', { 
    desc: 'Name of the new component', 
    }) 
} 

/* eslint-disable no-unused-expressions */ 
require('yargs') 
    .command({ 
    command: 'create <name>', 
    desc: 'Create a new component', 
    builder: createBuilder, 
    handler: create, 
    }) 
    .demandCommand(1, 'A command is required') 
    .help() 
    .argv 

をし、私は、ユーザーが作成したコマンドの後に名前を指定しない場合は、カスタムエラーメッセージを提供したいと思います。私が代わりにdemandCommandとdemandOption( のそれぞれを使用することをお勧めします

は、それはそれを行う方法をドキュメントから私には明らかではない、とgithubの問題を通過しながら、私はこのコメント(#928)に出くわしましたこれは文書化されている)。

これらは 別途

あなたは位置引数とフラグ引数を設定することができ、私は

.demandCommand(1, 'You need to provide name for the new component') 

または

.demandOption('name', 'You need to provide name for the new component') 

でなく、運なしの組み合わせのすべての種類を試してみました。誰もこれを行う方法を知っていますか?

答えて

0

コマンドオプションyargsは、2種類の引数を取ることができます。

最初のものは義務<varName>です。なんらかの理由で、ユーザがvarNameを入力せずにコマンドを入力すると、ヘルプページが表示されます。

オプション:[varName]です。ユーザがコマンドを入力した場合、たとえ紛失したvarNameがあってもコマンドが実行されます。

エクストラ:無限のvarName変数を使用する場合は、のオプションにはspread operatorを指定できます。カスタムエラーメッセージを提供したい場合には言われていること<...varNames>または[...varNames]


なので、それについて行くのいくつかの方法があります。最初は、このいずれかになります。

const program = require('yargs') 
    .command('create [fileName]', 'your description',() => {}, argv => { 
     if(argv.fileName === undefined) { 
      console.error('You need to provide name for the new component') 
      return; 
     } 
     console.log(`success, a component called ${argv.fileName} got created.`) 
    }) 

Lodashもまたうまくいくfunction _.isUndefinedを提供します。


第二は、このいずれかになります。

const program = require('yargs') 
    .command('create <fileName>', 'A description',() => {}, argv => { 

    }).fail((msg, err, yargs) => { 
     console.log('Sorry, no component name was given.') 
    }) 

program.argv 

は、詳細については、こちらをyargs APIのfail documentationです。

+0

ありがとうございますが、これはyargs apiを使用したソリューションよりも回避策が多いと感じています。私が見ている問題は、-hが表示されるということです。 'create [fileName]新しいコンポーネントを作成する' fileNameをオプションとしてマーキングしますが、通信する必要があります。 – devboell

+0

2番目の例は*あなたの問題を修正しましたか? – Ovior

+0

本当は、まだ未定義のハンドラを呼び出すので、それを処理しなければなりません。また、私は他のエラーによって 'fail'が呼び出される原因がわからないので、それを理解するコードを追加する必要があります。さらに、console.log/errorによるユーザのフィードバックは、 'demandCommand'と' demandOption'によって返されたメッセージと一貫していません。私は 'demandPositional'のようなものを期待していました...私はgithubで問題を開くかもしれません。私はあなたの助けに感謝します! – devboell

関連する問題