Can I gulp-notify when a watched task completes?

249 views Asked by At

We have a gulpfile with ~12 tasks, 4 of which are activated by a gulp.watch. I would like to use gulp-notify when a task started by gulp.watch completes. I don't want gulp-notify to do anything if a task is run directly. Sample code below:

const
    debug = require("gulp-debug"),
    gulp = require("gulp"),
    notify = require("gulp-notify");

gulp.task("scripts:app", function () {
    return gulp.src(...)
        .pipe(debug({ title: "tsc" }))
        .pipe(...);                // <--- if i add notify here, 
                                   //      I will always get a notification
});

gulp.task("watch", function () {
    gulp.watch("ts/**/*.ts", ["scripts:app"]);
});

If I pipe to notify inside the 'scripts:app' task, it will make a notification every time that task runs, regardless of how that task was started. Again, I want to notify when the watched task completes.

I considered adding a task 'scripts:app:notify' that depends on 'scripts:app', but if possible I'd like to avoid creating "unnecessary" tasks.

I also tried the following:

gulp.watch("ts/**/*.ts", ["scripts:app"])
    .on("change", function (x) { notify('changed!').write(''); });

But that results in a notification for every file changed. I want a notification when the task completes.

In other words, if I run gulp scripts:app, I should not get a notification. When I run gulp watch and change a watched file, I should get a notification.

How can I do this?

1

There are 1 answers

0
sandrooco On BEST ANSWER

Try adding params to your build script:

function buildApp(notify){
    return gulp.src(...)
        .pipe(...)
        .pipe(function(){
            if (notify) {
                //drop notification
            }
        });
    });      
}

//Register watcher
gulp.watch("ts/**/*.ts", function(){
    var notify = true;
    buildApp(notify);
});

//Register task so we can still call it manually
gulp.task("scripts:app", buildApp.bind(null, false));

As you can see, buildApp is a simple function. It's callable through a watcher or a "normal" task registration.