【问题标题】:Is it possible to get filename in gulp4 gulp.watch Task?是否可以在 gulp4 gulp.watch 任务中获取文件名?
【发布时间】:2019-07-06 04:49:48
【问题描述】:

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

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】:

    来自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…...
    });
    

    【讨论】:

      猜你喜欢
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      • 2011-09-15
      • 1970-01-01
      相关资源
      最近更新 更多