是否有可能在gulp4 gulp.watch Task中获取文件名?

时间:2019-02-12 14:02:01

标签: javascript gulp watch gulp-4

例如,假设我有这个侦听器:

gulp.watch('../templates/**/*.tpl', gulp.series('template'));

和相关任务:

var template = gulp.task('template', function(done) {
    console.log(filename);
    done();
});

是否可以获取触发监视事件的当前.tpl文件的文件名,如果是,怎么办?

1 个答案:

答案 0 :(得分:0)

来自gulp.watch docs

const { watch } = require('gulp');

const watcher = watch(['input/*.js']);

watcher.on('all', function(path, stats) {
 console.log(`File ${path} was changed`);
});

您可以这样使用'path'信息:

function scripts(myPath) {
  console.log(`in scripts, path = ${myPath}`);

  return gulp.src(myPath)
    .pipe(gulp.dest('pathTest'));
};

function watch(done) {

  const watcher = gulp.watch(["../templates/**/*.tpl"]);

  watcher.on('change', function (path, stats) {
    scripts(path);
  });

  done();
}

exports.default = gulp.series(watch);

因此,像上面的示例一样重新排列代码:

const watcher = gulp.watch('../templates/**/*.tpl');
watcher.on('change', function (path,stats) {
  template(path);
};

function template(filename) {
    console.log(filename);
    return gulp.src…...
});