Gulp dest: warn if 2 tasks try to write to the sam

2019-09-03 08:54发布

问题:

I wonder if there is an easy way to detect if two tasks write to the same file.

In this example there is a /js directory alongside a /ts directory. The /ts will get transpiled to the same directory as the /js. There shouldn't be any collisions. The ask is that, if there are collisions, the ts will win; but, I would like to warn that there is a collision.

gulp.task('js', function() {
    return es.concat(
        gulp.src(config.src.path('js', '**', '*.js'))
            .pipe(gulp.dest(config.build.path(app, 'js')))
        //, ....
    );
});

gulp.task('ts', ['js'], function() {

    var tsResult = gulp.src(config.src.path('ts', '**', '*.ts'))
        .pipe(ts({
            declaration: true,
            noExternalResolve: true
        }));

    return es.concat([
        tsResult.dts.pipe(gulp.dest(
            config.build.path(app, 'definitions'))),

        tsResult.js.pipe(gulp.dest(
            config.build.path(app, 'js'))) // <--- same dest as js task
    ]);

})

Can I detect that the ts task is overwriting a file that the js task just put in place?

回答1:

Just an idea. You can pass a callback to gulp.dest like this:

gulp.src('lib/*.js')
  .pipe(uglify())
  .pipe(gulp.src('styles/*.css'))
  .pipe(gulp.dest(function(file) {
    if (fs.existsSync('something here')) { // it's a deprecated call, use a newer one
       console.warn("File exists", file);
    }
    // I don't know, you can do something cool here
    return 'build/whatever';
  }));

The feature is available since Gulp 3.8: https://github.com/gulpjs/gulp/blob/master/CHANGELOG.md#380

Other resources:

  • https://stackoverflow.com/a/29437418/99256
  • https://stackoverflow.com/a/29817916/99256