Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling gulp-watch conditionally with gulp-if (or something else)

Basically I want to setup my task so that if I do gulp less --watch it will watch, otherwise just do the build. This is what I have so far:

'use strict';

var gulp = require('gulp');
var less = require('gulp-less');
var gulpif = require('gulp-if');
var watch = require('gulp-watch');
var cli = require('minimist')(process.argv.slice(2));

gulp.task('less', function () {
  return gulp.src(['./client/styles/styles.less', './client/styles/libs.less'])
    .pipe(less({ sourceMap: !cli.production }))
    .pipe(gulp.dest('./dist/styles'))
    .pipe(gulpif(cli.watch, watch()));
});

What happens is that it still executes the watch, but doesn't pass any files. This also prevents the task from process.exit()ing..

I'm assuming I have to either wrap it in something, or use an alternate method (not gulp-if)..

like image 867
knownasilya Avatar asked Jun 11 '14 18:06

knownasilya


1 Answers

gulp-watch is an endless stream, so if called it will never allow the process to exit. Your task always call watch() in order to pass it to gulpif even when the if won't need it. This means you will be running an unattached watcher. Additionally, the watcher needs to be first in your pipe chain so it can re-trigger the remaining handlers.

What you need to do is use the command line argument to conditionally call and attach watch(). run a task that does the watching. Also, use gulp-plumber (https://github.com/floatdrop/gulp-plumber) to keep the stream working if you have an error after the watcher.

var plumber = require('gulp-plumber');
gulp.task('less', function () {
    var src = gulp.src(['./client/styles/styles.less', './client/styles/libs.less']);

    if (cli.watch) {  // watch() won't be called without the command line arg
        src = src.pipe(watch()).plumber(); 
    }

    return src.pipe(less({ sourceMap: !cli.production }))
        .pipe(gulp.dest('./dist/styles'));
});
like image 120
Travis Terry Avatar answered Oct 03 '22 01:10

Travis Terry