在 Gulp 中使用 Yargs

Using Yargs inside Gulp

我正在使用 yargs 在 gulp 命令中传递参数。我在检查参数的有效性以及标志是否存在时会发生什么情况时遇到问题。

更具体地说,这是我的 gulpfile.js:

'use strict';

var argv = require('yargs').options({
    'config': {
        alias: 'c',
        demandOption: true,
        default: 'default',
        describe: 'Choose a configuration file name',
        type: 'string'
      },
    'host': {
        alias: 'h',
        demandOption: false,
        default: '',
        describe: 'Replace the host starting with http://',
        type: 'string'
    }
}).argv;

gulp.task('config', function(){

// If argument -c is passed copy config file in path 
// configs/Config_{{argv.c}}.js into Config.js
    gulp.src('./app/jsx/constants/Config_' + argv.c + '.js')
      .pipe(rename({ basename: 'Config'}))
      .pipe(gulp.dest('./app/jsx/constants'))
})

如果我 gulp config -c something,一切都会按预期进行。

我想要的是:如果命令中未提供配置参数,则让 CLI 要求配置参数。

有没有人有这方面的经验?

我花了一点时间才弄明白,在 config 对象中注释掉您的 default 选项可以使它起作用。

如果 demandOption 设置为 true 应该 没有默认值 确实有意义!然而,文档似乎没有说明任何内容(而且它只是默默地失败了),请参阅 valid options keys.

与此理论一致的是,您的第二个非必需选项“host”即使在未定义或空 default: "" 的情况下也能正常工作。