How to get task name inside task in gulp

*爱你&永不变心* 提交于 2019-12-21 03:33:06

问题


I'm using gulp-plumber + gulp-notify and want to put task name in gulp-notify as a title. following is the code i wrote, thanks in advance.

gulp.task('SOMETASK', function() {
    return gulp.src(sourcePaths)
        .pipe(plumber({errorHandler: notify.onError({
            message: "<%= error.message %>",
            title: "I WANT TO PUT TASK NAME HERE"
        })}))
        // omitted below

});

回答1:


gulp.Gulp.prototype.__runTask = gulp.Gulp.prototype._runTask;
gulp.Gulp.prototype._runTask = function(task) {
  this.currentTask = task;
  this.__runTask(task);
}

gulp.task("someTask", function(){
  console.log( this.currentTask.name );
}



回答2:


gulp.task('SOMETASK',function() {
    console.log('Task name:', this.seq.slice(-1)[0]) // Task name: SOMETASK
})



回答3:


If you want to monkey-patch Gulp, the following will work with Gulp version 3.9.0:

var _gulpStart = gulp.Gulp.prototype.start;

var _runTask = gulp.Gulp.prototype._runTask;

gulp.Gulp.prototype.start = function (taskName) {
    this.currentStartTaskName = taskName;

    _gulpStart.apply(this, arguments);
};

gulp.Gulp.prototype._runTask = function (task) {
    this.currentRunTaskName = task.name;

    _runTask.apply(this, arguments);
};

gulp.task('jscs', function () {
    console.log('this.currentStartTaskName: ' + this.currentStartTaskName);
    console.log('this.currentRunTaskName: ' + this.currentRunTaskName);
});

gulp.task('jshint', function () {
    console.log('this.currentStartTaskName: ' + this.currentStartTaskName);
    console.log('this.currentRunTaskName: ' + this.currentRunTaskName);
});

gulp.task('build', ['jshint', 'jscs']);

Running gulp build will yield the following console output:

c:\project>gulp build
[16:38:54] Using gulpfile c:\project\gulpfile.js
[16:38:54] Starting 'jshint'...
this.currentStartTaskName: build
this.currentRunTaskName: jshint
[16:38:54] Finished 'jshint' after 244 μs
[16:38:54] Starting 'jscs'...
this.currentStartTaskName: build
this.currentRunTaskName: jscs
[16:38:54] Finished 'jscs' after 152 μs
[16:38:54] Starting 'build'...
[16:38:54] Finished 'build' after 3.54 μs




回答4:


Define the task name outside of the callback and reference it where needed.

var taskName = 'SOMETASK';

gulp.task(taskName, function() {
    return gulp.src(sourcePaths)
        .pipe(plumber({errorHandler: notify.onError({
            message: "<%= error.message %>",
            title: taskName
        })}));
});


来源:https://stackoverflow.com/questions/27161903/how-to-get-task-name-inside-task-in-gulp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!