使用 gulp-watch with babel.js

Using gulp-watch with babel.js

下面是一个Gulp ES6 转译任务。它工作正常,但我正在尝试用 gulp-watch 插件替换 gulp.watch,以便捕获新文件。问题是 gulp-watch 没有给我 gulp.watch 在回调中做的事情,我不知道该怎么做。

这是我原来的工作任务:

var gulp = require('gulp'),
    rename = require('gulp-rename'),
    plumber = require('gulp-plumber'),
    gprint = require('gulp-print'),
    notify = require('gulp-notify'),
    babel = require('gulp-babel');

gulp.task('default', function() {
    return gulp.watch('../**/**-es6.js', function(obj){
        if (obj.type === 'changed') {
            gulp.src(obj.path, { base: './' })
                .pipe(plumber({
                    errorHandler: function (error) { /* elided */ }
                }))
                .pipe(babel())
                .pipe(rename(function (path) {
                    path.basename = path.basename.replace(/-es6$/, '');
                }))
                .pipe(gulp.dest(''))
                .pipe(gprint(function(filePath){ return "File processed: " + filePath; }));
        }
    });
});

这是我目前使用 gulp-watch 的所有内容:

var gulp = require('gulp'),
    rename = require('gulp-rename'),
    plumber = require('gulp-plumber'),
    gprint = require('gulp-print'),
    notify = require('gulp-notify'),
    babel = require('gulp-babel'),
    gWatch = require('gulp-watch');

gulp.task('default', function() {
    return gWatch('../**/**-es6.js', function(obj){
        console.log('watch event - ', Object.keys(obj).join(','));
        console.log('watch event - ', obj.event);
        console.log('watch event - ', obj.base);

        return;
        if (obj.type === 'changed') {
            gulp.src(obj.path, { base: './' })
                .pipe(plumber({
                    errorHandler: function (error) { /* elided */ }
                }))
                .pipe(babel())
                .pipe(rename(function (path) {
                    path.basename = path.basename.replace(/-es6$/, '');
                }))
                .pipe(gulp.dest(''))
                .pipe(gprint(function(filePath){ return "File processed: " + filePath; }));
        }
    });
});

日志的输出是这样的:

watch event - history,cwd,base,stat,_contents,event

watch event - change

watch event - ..

如何让 gulp-watch 向我提供我之前拥有的信息,或者,我如何更改我的任务代码以使其再次与 gulp-watch 一起工作?

根据 tests, obj.relative should contain the relative filename, and obj.path will still hold the absolute file path, just as it did in your original code. Also, the callback accepts a Vinyl object, which is documented here: https://github.com/wearefractal/vinyl

您可能无法在日志中看到它们,因为 Object.keys 没有枚举原型链中的属性。

使用 for..in 循环,您应该能够看到所有属性。