使用gulp-if(或其他)有条件地启用gulp-watch

kno*_*lya 5 javascript build gulp gulp-less gulp-watch

基本上我想设置我的任务,如果我这样做gulp less --watch会看,否则只是做构建.这是我到目前为止:

'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()));
});
Run Code Online (Sandbox Code Playgroud)

会发生什么是它仍然执行watch,但不传递任何文件.这也可以防止任务进入process.exit()..

我假设我必须将其包装在某物中,或使用替代方法(不是gulp-if).

Tra*_*rry 6

gulp-watch是一个无穷无尽的流,所以如果被调用它永远不会允许进程退出.您的任务始终会调用watch(),以便将其传递给gulpifif ,即使if不需要它也是如此.这意味着您将运行一个独立的观察者.此外,观察者需要首先在您的管道链中,以便它可以重新触发剩余的处理程序.

您需要做的是使用命令行参数有条件地调用和附加watch().运行一个观察任务.此外,如果在观察者之后发生错误,请使用gulp-plumber(https://github.com/floatdrop/gulp-plumber)保持流正常工作.

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'));
});
Run Code Online (Sandbox Code Playgroud)

  • 我找到了一个工作,不完全像你的,但它也有效.我正在使用`pipe(cli.watch?watch():gutil.noop())`.谢谢你的解决方案. (2认同)