命令未使用 yarg npm 包添加

command is not adding using yarg npm package

我正在尝试使用 yarg 添加命令,但是当我 运行 我的代码时,我的命令没有被添加。

这是我正在尝试的:

const yargs = require('yargs')

//create add command
yargs.command({
    command: 'add',
    describe: 'to add note',
    handler: function() {
        console.log('note has been added')
    } 
})

运行 命令:

PS C:\Users\HP\Desktop\node\notes-app> node app.js --help
Options:
  --help     Show help                                                 [boolean]
  --version  Show version number                                       [boolean]

没有添加命令。

此外,当我尝试通过将添加作为参数(即节点 app.js 添加)来 运行 我的代码时,什么也没有显示。

我现在该怎么办?

根据 yargs 文档,方法 command 需要 4 个参数而不是对象;

.command(cmd, desc, [builder], [handler])

所以你的代码应该是这样的(注意,没有更多的括号和对象键):

//create add command
yargs.command(
    'add',
    'to add note',
    function() {
        console.log('note has been added')
    } 
})

如果您没有传递可选的 builder 参数,可能应该为处理程序函数使用命名参数(不确定 yargs 是如何命名参数的,但我猜它是 handler) 喜欢

   ...
   handler = function() {
        console.log('note has been added')
    }
yargs.command({
    command: 'add',
    describe: 'to add note',
    handler: function() {
        console.log('note has been added')
    } 
}).parse()

如果你不添加parse(),yargs将不会执行。如果你有太多 yargs 命令类型

yargs.parse()

console.log(yargs.argv)

在下面。