12

我正在尝试编写一个通过gulp-prompt 插件获取一些用户输入的 gulp 任务。但是我无法将该输入传递给其他例如:

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

    var myVar = 'MONKEY';

    gulp.src('./templates/_component.*')
    .pipe(prompt.prompt([
        {
            type: 'input',
            name: 'userInput',
            message: 'Say something'
        }
    ], function(res){
        myVar = res.userInput;
    }))
    .pipe(prompt.confirm('You said ' + myVar));
});

假设我hello在提示符下输入,我期待确认说You said Hello,但它说You said MONKEY

Gulp 可以吗?

4

1 回答 1

18

这里的问题是您在执行第一个提示之前'You said ' + myVar创建了第二个提示 ( ) :

  1. 设置myVar'MONKEY'
  2. 创建流
    1. 创建src流,这是异步的
    2. 创建第一个提示,并将其添加到 src 流
    3. 使用 的当前值创建第二个提示myVar,并将其添加到第一个提示流
  3. 只有现在才处理执行的流
    1. 加载源
    2. 运行第一个提示,设置myVar
    3. 使用先前生成的消息运行第二个提示

如果要将其全部保留为单个流,唯一的解决方案是在允许闭包(函数)的东西中使用变量。一些插件已经接受闭包作为参数,但大多数不接受。

将流包装在一个可以在这里工作的闭包中的一种解决方案是gulp-tap,它不是专门为这种情况设计的,但应该可以工作。它看起来像这样:

var tap = require('gulp-tap');

//...

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

    var myVar = 'MONKEY';

    gulp.src('./templates/_component.*')
    .pipe(prompt.prompt([
        {
            type: 'input',
            name: 'userInput',
            message: 'Say something'
        }
    ], function(res){
        myVar = res.userInput;
    }))
    .pipe(tap(function(file, t) {
        // format is t.through(stream-function, [arguments...])
        return t.through(prompt.confirm, ['You said ' + myVar]);
    });
});

因为它被包装在一个闭包中,并针对每个文件进行评估,所以它将获取变量的当前值。 但是,因为它适用于每个文件,所以对于每个处理的文件,您都会看到一次提示。


更好的解决方案是将您的任务分成多个相关的任务。看起来像这样:

var myVar = 'MONKEY';

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

    return gulp.src('./templates/_component.*', {read: false})
        .pipe(prompt.prompt([
            {
                type: 'input',
                name: 'userInput',
                message: 'Say something'
            }
        ], function(res){
            myVar = res.userInput;
        }));
});

gulp.task('userinput', ['userinput1'], function() {
    return gulp.src('./templates/_component.*')
        .pipe(prompt.confirm('You said ' + myVar));
});

现在第一个任务 ( ) 将在处理第二个任务 ( )之前userinput1运行并完成,因此将正确设置变量。userinput2

注意:确保您return从任务中获取流,否则它们会被同步处理,并且您的变量不会被设置。


最后,完全放弃任务可能更有意义gulp-prompt,因为它与流并没有太大关系。您最好在任务中直接使用 Node JavaScript 来收集用户的输入(最好以同步方式),然后在 gulp-stream 中处理您的文件。

于 2014-02-25T22:46:22.527 回答