4

I'm having a strange problem. I'm using gulp to compile a react app and am having it copy index.html to the appropriate web directory. When I first run gulp, all runs as expected, but when the file changes and the watch task is run, gulp copies an empty version of the file to the web directory. Does anyone know why this might be happening? Here is my gulpfile.js:

var gulp = require('gulp');

var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');

var livereload = require('gulp-livereload');

gulp.task('livereload', function() {
    console.log('reloading');
    livereload();
});

gulp.task('copyindextodist', function() {
    gulp.src('app/index.html')
        .pipe(gulp.dest('dist'));
});

gulp.task('compilejs', function() {
    browserify({
        entries: 'app/index.js',
        extensions: ['.js'],
        debug: true
    })
    .transform('babelify', {presets: ['es2015', 'react']})
    .bundle()
    .pipe(source('app.js'))
    .pipe(gulp.dest('dist'));
});

gulp.task('publishapp', function() {
    gulp.src('dist/*.*')
        .pipe(gulp.dest('../public'));
});

gulp.task('copypaste', function() {
    gulp.src('app/index.html')
        .pipe(gulp.dest('../public'));
});

gulp.task('watch', function() {
    livereload.listen();
    gulp.watch('app/index.html', ['copyindextodist']);
    gulp.watch('dist/index.html', ['publishapp']);
    gulp.watch('app/index.js', ['compilejs']);
    gulp.watch('dist/app.js', ['publishapp']);
});

gulp.task('default', ['copyindextodist', 'compilejs', 'publishapp', 'watch']);
user2027202827
  • 1,234
  • 11
  • 29

1 Answers1

0

I had the same problem until I defined the dependencies correctly. You can define which tasks should be completed, before the current task starts:

gulp.task('compress', ['copy'], function() {
    //.... your job
});

This means that the compress task will wait for the copy task to be finished. If you don't do that, you might end up with empty/truncated files and other strange results.

Just take care that your copy tasks return a stream object.

gulp.task('copy', function() {
    // "return" is the important part ;-)
    return gulp.src(['filepath/**/*']) 
        .pipe(gulp.dest('lib/newpath'))
});

If you have multiple copy commands running in your task this is tricky, but there is an extension for this:

var gulp = require('gulp');
var merge = require('merge-stream');
gulp.task('copy', function() {
    var allStreams = [
        gulp.src(['node_modules/bootstrap/dist/**/*'])
             .pipe(gulp.dest('lib/bootstrap')),
        gulp.src(['node_modules/jquery/dist/**/*'])
             .pipe(gulp.dest('lib/jquery')),
    ];
    return merge.apply(this, allStreams);
});
gulp.task('nextTask', ['copy'], function() {
    // this task formerly produced empty files, but now
    // has a valid dependency on the copy stream and 
    // thus has all files available when processed.
});
ESP32
  • 8,089
  • 2
  • 40
  • 61