使用gulp-watch运行现有任务

时间:2015-01-14 20:52:14

标签: javascript gulp gulp-watch

我已经在gulpfile.js中定义了一些任务,我想使用gulp-watch插件(在新文件上运行任务)。我的问题是,因为我找不到任何东西,我可以在运行watch(来自插件)功能时运行我现有的任务吗?

var gulp = require('gulp'),
    watch = require('gulp-watch'),
    ...;

gulp.task('lint', function () {
  return gulp.src(path.scripts)
      .pipe(jshint())
      .pipe(jshint.reporter(stylish));
});

gulp.task('watch', function () {
  watch({ glob: 'app/**/*.js' }); // Run 'lint' task for those files
});

因为我不想在我的每项任务中加入watch()任务。我想只有一项任务 - 观看,它将结合所有"手表"。

-----编辑---- (因为我可能没有完全理解我的观点):

我需要从gulp('watch')任务内部运行任务。例如:

就像我用gulp.watch

做的那样
gulp.task('watch', function () {
  gulp.watch('files', ['task1', 'task2']);
});

我需要使用gulp-watch插件执行相同操作,例如(我知道它不会起作用):

var watch = require('gulp-watch');

gulp.task('watch', function () {
  watch({ glob: 'files' }, ['task1', 'task2']);
});

4 个答案:

答案 0 :(得分:24)

I have also run into the problem of wanting to use gulp-watch (not gulp.watch), needing to use the callback form, and having trouble finding a suitable way to run a task in the callback.

My use case was that I wanted to watch all stylus files, but only process the main stylus file that includes all the others. Newer versions of gulp-watch may address this but I'm having problems with 4.3.x so I'm stuck on 4.2.5.

  • gulp.run is deprecated so I don't want to use that.
  • gulp.start works well, but is also advised against by the gulp author, contra.
  • The run-sequence plugin works well and lets you define a run order, but it is a self-proclaimed hack: https://www.npmjs.com/package/run-sequence
  • Contra suggest writing plain old functions and calling those. This is a new idea to me, but I think the example below captures the idea. https://github.com/gulpjs/gulp/issues/505

Take your pick.

var gulp = require('gulp'),
    watch = require('gulp-watch'), // not gulp.watch
    runSequence = require('run-sequence');

// plain old js function
var runStylus = function() {
    return gulp.src('index.styl')
        .pipe(...) // process single file
}

gulp.task('stylus', runStylus);

gulp.task('watch', function() {
    // watch many files
    watch('*.styl', function() {
        runSequence('stylus');
        OR 
        gulp.start('stylus');
        OR
        runStylus();
    });
});

All of these are working for me without warnings, but I'm still unsure about getting the "done" callback from the 4.2.x version of gulp-watch.

答案 1 :(得分:13)

您很可能希望运行与您正在观看的文件相关的特定任务 -

gulp.task('watch',['lint'], function () {
    gulp.watch('app/**/*.js' , ['lint']);
});

您还可以使用['lint']部分在首次调用监视时运行任何所需任务,或者利用任务与

运行异步
gulp.task('default', ['lint','watch'])

答案 2 :(得分:7)

您只需调用一个任务,然后包含任务

gulp.task('default', ['lint','watch'])

所以在这里你只需要打电话' gulp'

答案 3 :(得分:4)

gulp.task('watch', function() {
  watch(files, function() {
    gulp.run(['task1', 'task2']);
  });
});

工作正常,但警告

除外