Search code examples
javascriptgulpecmascript-6gulp-watchbabeljs

Transpile into ES 5 using babel by gulp-watch not working


I am new to gulp.I am trying to setup a watch so that my src/main.js file is transpiled to dist/main.js file. The Gulpfile has the following code

var gulp = require('gulp');
var babel = require('gulp-babel');
var watch = require('gulp-watch');
var paths = {
    babel:"src/main.js"
}

gulp.task('babel', function() {
    return gulp.src(paths.babel)
        .pipe(watch(paths.babel))
        .pipe(babel())
        .pipe(gulp.dest('dist/'))
})
gulp.task('default', ['babel']);

My dist/main.js file does not reflect changes from src/main.js . Any help as to where I am going wrong would be appreciated.


Solution

  • Try the following (and make sure you execute gulp watch, not just gulp):

    var gulp = require('gulp');
    var babel = require('gulp-babel');
    var watch = require('gulp-watch');
    var rimraf = require('rimraf');
    var paths = {
      babel: 'src/main.js',
      build: 'dist'
    };
    
    gulp.task('clean', function(cb) {
      rimraf(paths.build, cb);
    });
    
    gulp.task('build', ['clean'], function() {
      return gulp
        .src(paths.babel)
        .pipe(babel())
        .pipe(gulp.dest(paths.build));
    });
    
    gulp.task('watch', ['build'], function() {
      return watch(paths.babel, function() {
        gulp.start('build');
      });
    });
    
    gulp.task('default', ['build']);
    

    If that doesn't work, maybe your paths.babel is wrong. Try changing it to src/**/*.js.