题
我试图编写一个gulp任务,通过 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?
解决方案
这里的问题是您正在创建第二个提示符('You said ' + myVar
) 以前 已执行第一个提示:
- 套装
myVar
到'MONKEY'
- 创建流
- 创建
src
流,这是异步的 - 创建第一个提示符,并将其添加到src流中
- 使用当前值创建第二个提示
myVar
, ,并将其添加到第一提示流中
- 创建
- 现在才处理执行的流
- 负载源
- 运行第一个提示符,设置
myVar
- 使用先前生成的消息运行第二个提示
如果您想将其全部保留为单个流,唯一的解决方案是在允许闭包(函数)的内容中使用变量。一些插件已经接受闭包作为参数,但大多数不接受。
在这里工作的闭包中包装流的一种解决方案是 大口-水龙头, ,它不是专门为这种情况设计的,但应该工作。它看起来像这样:
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
任务完全,因为它与流没有太大关系。你可能会更好地在你的任务中使用直节点JavaScript来收集用户的输入(最好以同步的方式),然后在一个gulp流中处理你的文件。
不隶属于 StackOverflow