我正在尝试编写一个 gulp 任务,通过 gulp-prompt plugin 接收一些用户输入.但我无法将该输入传递给其他人,例如:
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
- 使用先前生成的消息运行第二个提示
如果您想将所有内容都保留为单个流,唯一的解决方案是在允许闭包(函数)的内容中使用变量。一些插件已经接受闭包作为参数,但大多数不接受。
将流包装在此处适用的闭包中的一种解决方案是 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
) 之前运行并完成,因此变量将是正确设置。
NOTE: Make sure you
return
the stream from your tasks, otherwise they are processed synchronously, and your variable won't get set.
最后,完全放弃 gulp-prompt
任务可能更有意义,因为它实际上与流没有太大关系。您最好在任务中直接使用 Node JavaScript 来收集用户的输入(最好以同步方式),然后在 gulp-stream 中处理您的文件。
关于javascript - 在 Gulp 中的 "pipes"之间传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22026389/