首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >确定是否从另一个任务调用Gulp任务

确定是否从另一个任务调用Gulp任务
EN

Stack Overflow用户
提问于 2014-09-19 07:02:24
回答 1查看 745关注 0票数 1

是否有一种方法可以确定某个任务是直接调用的,还是从另一个任务调用的?

代码语言:javascript
复制
  runSequence = require 'run-sequence'

  gulp.task 'build', ->
     ....

  gulp.task 'run', ->
     runSequence 'build', -> gulp.start('server')

我需要一个if案例在build任务中说:如果它被直接调用- (gulp build),那么做些什么;

或者,如果它是从run任务调用的,那么执行其他操作

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-20 01:30:36

这可能是一个X/Y problem。你到底想做什么?

,但要回答这个问题,;我认为唯一的方法是查看调用堆栈跟踪,并确保只有Gulp才能触及任务。我写了一个函数来找出谁策划了这个任务。您只需将该函数与您的gulpfile.js内联,并像布尔值一样使用它。

下面的代码依赖于npm parse-stack,所以请确保npm install parse-stack

用法:if(wasGulpTaskCalledDirectly()) { /*...*/ }

代码语言:javascript
复制
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

代码语言:javascript
复制
// 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
	);
});

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25928170

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档