首页 > 解决方案 > 获取未为 yargs.getHelp() 定义的函数

问题描述

我希望获得由 yargs.getHelp() 产生的自动生成的帮助,但我收到了一个错误,即该函数未定义。这是示例代码:

const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');
const { parsed, boolean } = require("yargs");


async function parseArgs(){

    let parsedArgs = yargs(hideBin(process.argv))
        .option("trend-file", {
            alias: "t",
            description: "The full filename of the trendfile.",
            type: "string",
        })
        .option("start-time", {
            alias: "s",
            description: "Start time for trend.",
            type: "string",
        })
        .argv;

    const test = await yargs.getHelp();
    console.log(test);
}

parseArgs()
.catch((e)=>{console.log(e.message);});

注意:这只是对较大代码库的提取。注释调用 yargs.getHelp() 的行可以正常工作。我觉得我只是做错了。有人有一个工作的例子吗?

我正在使用 yargs v17.2.1

更新---我能够通过将所有选项传递给 yargs() 然后像这样调用 getHelp() 来获得帮助:

let test = await yargs()
    .option("trend-file", {
        alias: "t",
        description: "The full filename of the trendfile.",
        type: "string",
    })
    .option("start-time", {
        alias: "s",
        description: "Start time for trend.",
        type: "string",
    })
    .getHelp();

有没有更好的方法来做到这一点而不列出所有选项两次?

标签: node.jsyargs

解决方案


我做错了。所需要的只是首先将 yargs 对象返回给一个变量,然后使用它来分别使用 argv 获取参数列表和使用 getHelp() 获取帮助。最终代码应如下所示:

const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');
const { parsed, boolean } = require("yargs");


async function parseArgs(){

    let parsedArgs = await yargs(hideBin(process.argv))
        .option("trend-file", {
            alias: "t",
            description: "The full filename of the trendfile.",
            type: "string",
        })
        .option("start-time", {
            alias: "s",
            description: "Start time for trend.",
            type: "string",
        });

    let args = parsedArgs.argv;
    const help = await parsedArgs.getHelp();
    console.log(help);
}

parseArgs()
.catch((e)=>{console.log(e.message);});


推荐阅读