gulp如何在忽略某些模式的同时使用gulp同步文件夹

时间:2015-04-26 11:52:42

标签: gulp

我想使用gulp同步两个文件夹。我已经设法用一个名为gulp-directory-sync的包来实现这个目的(参见下面的包含任务),但是现在我需要根据文件或目录名称以“__”开头的方式从同步中排除一些文件(两个下划线) )。我试图找到一个带有忽略或排除功能的同步插件,但没有成功,所以我现在想知道是否有人可能知道解决方法。

var gulp = require('gulp');
var dirSync = require('gulp-directory-sync');

gulp.task('sync', function () {
  return gulp.src('')
    .pipe(dirSync('./one', './two'));
});

1 个答案:

答案 0 :(得分:6)

我总是非常怀疑“插件”谁在第一行打破了通路。如果您不需要gulp-src中的文件,那么您可能不需要为这项任务做任何事情,或者还有其他一些可疑的事情。

Gulp已经非常善于将文件复制到其他地方,包括异常,那么为什么不使用这种内置功能呢?使用gulp-newer插件,我们可以确保只复制那些已更新的文件:

var gulp = require('gulp');
var newer = require('gulp-newer');
var merge = require('merge2');

gulp.task('sync', function(done) {

    return merge(
        gulp.src(['./one/**/*', '!./one/**/__*'])
            .pipe(newer('./two'))
            .pipe(gulp.dest('./two')),
        gulp.src(['./two/**/*', '!./two/**/__*'])
            .pipe(newer('./one'))
            .pipe(gulp.dest('./one'))
    );
});

以下是带有注释的相同代码:

var gulp = require('gulp');
var newer = require('gulp-newer');
var merge = require('merge2');

gulp.task('sync', function(done) {

    return merge(
        // Master directory one, we take all files except those
        // starting with two underscores
        gulp.src(['./one/**/*', '!./one/**/__*'])
        // check if those files are newer than the same named
        // files in the destination directory
            .pipe(newer('./two'))
        // and if so, copy them
            .pipe(gulp.dest('./two')),
        // Slave directory, same procedure here
        gulp.src(['./two/**/*', '!./two/**/__*'])
            .pipe(newer('./one'))
            .pipe(gulp.dest('./one'))
    );
});

这也可以解决问题,不需要插件; - )

<强>更新

假设您只想从one复制到two,并且您可能正在运行一个观察程序,您可以使用gulp中的“已删除”事件来检查哪个文件已经消失:< / p>

var gulp = require('gulp');
var newer = require('gulp-newer');
var path = require('path');
var del = require('del');

gulp.task('sync', function(done) {
    return gulp.src(['./one/**/*', '!./one/**/__*'])
        .pipe(newer('./two'))
        .pipe(gulp.dest('./two'));
});

gulp.task('default', function() {
    var watcher = gulp.watch('./one/**/*', ['sync']);
    watcher.on('change', function(ev) {
        if(ev.type === 'deleted') {
            // path.relative gives us a string where we can easily switch
            // directories
            del(path.relative('./', ev.path).replace('one','two'));
        }
    });
});