有没有办法确定是直接调用任务还是从其他任务调用?
runSequence = require 'run-sequence'
gulp.task 'build', ->
....
gulp.task 'run', ->
runSequence 'build', -> gulp.start('server')
我在if
任务中需要build
个案例说:
如果是直接调用 - (gulp build
)然后做某事;
或者如果从run
任务调用它,那么就做其他事情
答案 0 :(得分:1)
这可能是X/Y problem。你到底想要完成什么?
但要回答这个问题;我认为唯一的方法是查看调用堆栈跟踪并确保只有Gulp接触任务。我写了一个函数,找到谁策划了任务。您可以将函数与gulpfile.js
内联,并将其用作布尔值。
以下代码依赖于npm parse-stack
,因此请务必npm install parse-stack
用法:if(wasGulpTaskCalledDirectly()) { /*...*/ }
function wasGulpTaskCalledDirectly()
{
var parseStack = require("parse-stack");
var stack = parseStack(new Error());
// Find the index in the call stack where the task was started
var stackTaskStartIndex = -1;
for(var i = 0; i < stack.length; i++)
{
if(stack[i].name == 'Gulp.Orchestrator.start')
{
stackTaskStartIndex = i;
break;
}
}
// Once we find where the orchestrator started the task
// Find who called the orchestrator (one level up)
var taskStarterIndex = stackTaskStartIndex+1;
var isValidIndex = taskStarterIndex > 0 && taskStarterIndex < stack.length;
if(isValidIndex && /gulp\.js$/.test((stack[taskStarterIndex].filepath || "")))
{
return true;
}
return false;
}
您可以在下面找到用于测试的完整gulpfile.js
:
// This is a test for this SE question: http://stackoverflow.com/q/25928170/796832
// Figure out how to detect `gulp` vs `gulp build`
// Include gulp
var gulp = require('gulp');
var runSequence = require('run-sequence');
// Add this in from the above code block in the answer
//function wasGulpTaskCalledDirectly()
// ...
gulp.task('build', function() {
//console.log(wasGulpTaskCalledDirectly());
if(wasGulpTaskCalledDirectly())
{
// Do stuff here
}
else
{
// Do other stuff here
}
return gulp.src('./index.html', {base: './'})
.pipe(gulp.dest('./dist'));
});
// This does nothing
gulp.task('start-server', function() {
return gulp.src('./index.html', {base: './'});
});
// Default Task
gulp.task('default', function(callback) {
runSequence('build',
['start-server'],
callback
);
});