我正在尝试 运行 yargs 命令,但它不起作用

I am trying to run yargs command, and it is not working

我是运行:

node app.js add

而我的代码是:

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

但控制台上没有打印任何内容。

正如上面评论中提到的@jonrsharpe。

您需要致电 parse function or access argv 属性

尝试:

const yargs = require('yargs');

yargs
    .command({
        command:'add',
        describe:'Adding command',
        handler: argv => {
            console.log('Adding notes');
        }
    })
    .parse();

或者

const yargs = require('yargs');

const argv = yargs
    .command({
        command: 'add',
        describe: 'Adding command',
        handler: argv => {
            console.log('Adding notes');
        }
    })
    .argv;

node index.js add

您必须提供 yargs.parse();或 yargs.argv; 在定义所有命令后。

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

yargs.parse();
//or
yargs.argv;

You can .argv or .parse() specify individually

    yargs.command({
        command:'add',
        describe:'Adding command',
        handler:function(){
            console.log('Adding notes');
        },
    }).parse() or .argv;

只要一个命令就可以了。但是对于多个命令,定义所有命令后最后执行yargs.argv。

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

示例解决方案:

const yargs = require('yargs')

//add command
yargs.command({
    command: 'add',
    describe: 'Add a new note',
    handler: ()=>{
        console.log("Adding a new note")
    }
})
//remove Command
yargs.command({
    command: 'remove',
    describe: "Remove a Note",
    handler: ()=>{
        console.log("removing note")
    }
})

yargs.parse()

我也遇到了这个问题,通过最新的node.js更新找到了解决方案。您需要将文件扩展名从 .js 更改为 .cjs 并且它可以正常工作。