Search code examples
javascriptgulpbabeljsgulp-watch

Gulp-babel doesn't transpile when watching


The task 'babel' seems to work good. On the other hand, when watching, if I change the es6 file it doesn't transpile even though the browser reloads. And it reloads only because it is in the task 'babel'.

Here is my gulpfile:

var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');

/* ----------------- */
/* Styles
/* ----------------- */

gulp.task('sass', function() {
  return gulp.src('app/scss/*.+(scss|sass)') // Gets all files ending with .scss in app/scss
    .pipe(sass())
    .pipe(gulp.dest('app/css'))
    .pipe(browserSync.reload({
      stream: true
    }))
});

/* ----------------- */
/* Development
/* ----------------- */

gulp.task('watch', ['browserSync', 'sass', 'babel'], function(){
  gulp.watch('app/scss/*.+(scss|sass)', ['sass']);
  gulp.watch('app/*.html', browserSync.reload);
  gulp.watch('**/*.js', browserSync.reload);
  gulp.watch('app/es6/*.js', ['babel'])
})

gulp.task('browserSync', function() {
  browserSync.init({
    server: {
      baseDir: 'app'
    },
  })
})

/* ----------------- */
/* Scripts
/* ----------------- */

gulp.task('babel', () =>
    gulp.src('app/es6/*.+(js)')
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(sourcemaps.init())
        .pipe(concat('scripts.js'))
        .pipe(gulp.dest('app/js'))
        .pipe(browserSync.reload({
          stream: true
        }))
);

Solution

  • The problem is in the babel task, in the source file. It should be changed to:

       /* ----------------- */
       /* Scripts
       /* ----------------- */
    
    
       gulp.task('babel', () =>
           gulp.src('app/js/es6/*.js')
               .pipe(babel({
                   presets: ['env']
               }))
               .pipe(sourcemaps.init())
               .pipe(concat('main.js'))
               .pipe(gulp.dest('app/js/es5/'))
               .pipe(browserSync.reload({
                 stream: true
               }))
       );
    

    Otherwise it created a new directory where it was reading the file from app/js/app/es6. So the changes in app/es6/ would be watched (because of the task watch) and the browser would reload, but the .js file wouldn't be transpiled.

    And, just as a side note: there was some bad globbing:

        gulp.watch('app/js/*.js', browserSync.reload)
    

    It should be taken out or at least changed to:

        gulp.watch('gulpfile.js', browserSync.reload);
    

    Otherwise it also watches all the app dependencies, which drastically slows down watching.