有没有一种方法可以让watch函数获取被监视文件的名称

Is there a way to have a watch function get the name of the file being watched?

本文关键字:获取 函数 监视 文件 watch 一种 方法 有没有      更新时间:2024-05-09

我已经对这三块手表进行了编码,但还需要编码更多:

gulp.task('fl-index', function () {
    gulp.watch('index-fl.html', function () {
        return gulp.src('index-fl.html')
          .pipe(rename('index.html'))
          .pipe(gulp.dest('./'));
    })
});
gulp.task('ic-index', function () {
    gulp.watch('index-ic.html', function () {
        return gulp.src('index-ic.html')
          .pipe(rename('index.html'))
          .pipe(gulp.dest('./'));
    })
});
gulp.task('ts-index', function () {
    gulp.watch('index-ts.html', function () {
        return gulp.src('index-ts.html')
          .pipe(rename('index.html'))
          .pipe(gulp.dest('./'));
    })
});

由于所有的功能几乎都是一样的,我想知道我是否有可能以某种方式将其组合成一口吞下的任务?

每次发生更改时,传递给gulp.watch()的函数都会接收一个对象,该对象包含指向受影响文件的path属性。

您可以使用它来统一您的三项任务:

var gulp   = require('gulp');
var rename = require('gulp-rename');
var path = require('path');
gulp.task('index', function () {
  gulp.watch('index-*.html', function (file) {
    return gulp.src(path.basename(file.path))
      .pipe(rename('index.html'))
      .pipe(gulp.dest('./'));
  })
});