是否可以在gulp4 gulp.watch任务中获取文件名?

问题描述 投票:0回答:1

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

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

以及相关的任务:

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

是否有可能获取当前.tpl文件的文件名,该文件已触发监视事件,如果是,如何?

javascript gulp watch gulp-4
1个回答
1
投票

来自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…...
});
© www.soinside.com 2019 - 2024. All rights reserved.