Yargs – 如何为省略位置参数提供自定义错误消息

我无法find正确configuration位置参数的方法。 我有这个代码:

#!/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 

我想提供一个自定义的错误消息,以防用户在create命令之后没有指定一个名字。

从文档中我不清楚如何做到这一点,而在处理github问题时,我碰到了这个评论(#928):

我build议使用demandCommand和demandOption(每个都有文档)。

这些允许您分别configuration位置参数和标志参数

我已经尝试了各种组合

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

要么

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

但没有运气。 有人知道怎么做这个吗?

yargs的命令选项可以有两种types的参数。

第一个是必须的: <varName> 。 如果由于某种原因,用户input命令而不inputvarName ,那么它将运行帮助页面。

第二个是可选[varName] 。 如果用户input命令,即使缺lessvarName ,命令也会运行。

额外:如果你想要无限的varNamevariables,那么你可以为想要的选项提供一个扩展运算符 。 正在<...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还提供了一个函数_.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上的失败文档 。