Gulp:如何将参数从watch传递给任务

and*_*dig 4 gulp gulp-watch

有了吞咽,你经常会看到这样的模式:

gulp.watch('src/*.jade',['templates']);

gulp.task('templates', function() {
  return gulp.src('src/*.jade')
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest('dist/'))
    .pipe( livereload( server ));
});
Run Code Online (Sandbox Code Playgroud)

这实际上是将watcheded文件传递给模板任务吗?这些如何覆盖/扩展/过滤src的任务?

caa*_*sjj 8

我前段时间遇到了同样的问题,并在挖掘了一下之后得出了以下结论.

gulp.watch是一个发出change事件的eventEmitter,所以你可以这样做:

var watcher = gulp.watch('src/*.jade',['templates']);

watcher.on('change', function(f) {
  console.log('Change Event:', f);
});
Run Code Online (Sandbox Code Playgroud)

你会看到这个:

Change Event: { type: 'changed',
  path: '/Users/developer/Sites/stackoverflow/src/touch.jade' }
Run Code Online (Sandbox Code Playgroud)

这些信息可能template通过其任务函数或行为传递给任务gulp.src.

任务函数本身只能接收回调(https://github.com/gulpjs/gulp/blob/master/docs/API.md#fn)并且无法接收有关乙烯基文件的任何信息(https://github.com gulp使用/ wearefractal/vinyl-fs).

启动任务的源(.watch在这种情况下,或gulp命令行)对行为没有影响gulp.src('src-glob', [options]).'src-glob'是一个字符串(或字符串数​​组)和options(https://github.com/isaacs/node-glob#options)没有任何文件更改.

因此,我认为没有任何方式.watch可以直接影响它触发的任务的行为.

如果您只想处理更改的文件,可以使用gulp-changed(https://www.npmjs.com/package/gulp-changed),如果您想使用gulp.watch,或者冷使用gulp-watch.

或者,您也可以这样做:

var gulp = require('gulp');
var jade = require('gulp-jade');
var livereload = require('gulp-livereload');

gulp.watch('src/*.jade', function(event){
  template(event.path);
});

gulp.task('templates', function() {
  template('src/*.jade');
});

function template(files) {
  return gulp.src(files)
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest('dist/'))
}
Run Code Online (Sandbox Code Playgroud)