【问题标题】:yargs.command is not working (error msg: yargs.command is not a function)yargs.command 不起作用(错误消息:yargs.command 不是函数)
【发布时间】:2021-05-06 13:07:45
【问题描述】:

我正在尝试创建 yargs 命令,当我运行应用程序时出现错误。

当我运行以下命令时:

node app.js add

在我的 node.js 代码上:

const yargs = require('yargs')
yargs.command({
    command:'add',
    describe:'Adding command',
    handler:function(){
        console.log('Adding notes')
    }
}).parse()

console.log('yargs.argv')

错误:

C:\node\notes-app\app.js:3
yargs.command({
      ^
**TypeError: yargs.command is not a function**
    at Object.<anonymous> (C:\node\notes-app\app.js:3:7)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

  • Yargs 版本:1.1.0
  • 节点版本:v14.16.0
  • vs 代码版本
  • 1.55.2(用户设置)操作系统:Window 10

编辑: (I have already viewed this question but it didn't help because already added .parse())

【问题讨论】:

    标签: node.js yargs


    【解决方案1】:

    尝试以下几行。

    const yargs = require('yargs')
    const {hideBin} = require('yargs/helpers')
    yargs(hideBin(process.argv)).command({
        command:'add',
        describe:'Adding command',
        handler:function(){
            console.log('Adding notes')
        }
    }).parse()
    console.log('yargs.argv')
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    Yargs 1.1.0 是很久以前的事了,实际上是 7 年。那时他们没有.command() 方法。

    https://www.npmjs.com/package/yargs/v/1.1.0

    最简单的解决方案就是更新。您应该能够使用节点 v14.16 至少转到 v14 或 v15。

    如果您不想这样做,则需要添加自己的小型命令解析器:

    const argv = require('yargs').argv;
    
    if(argv._[0] === "add") {
       // ...
    } 
    

    【讨论】:

      猜你喜欢
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      • 2018-06-26
      • 2021-12-16
      相关资源
      最近更新 更多