Search code examples
npmgulp

How to migrate to gulp v4 from 3?


gulp.watch('watch', function() {
 watch('./app/index.html', function() {
  gulp.start('html');
 });
});

I want to run a task named 'html' when any changes to the file are made. It worked in the previous version of gulp for as for now it generates the following error. gulp.start is not a function.

I can't find any way to achieve this in the newer version of the gulp. All I found that I need to change it to function, but I can't seem to find what I need to change and how?

The rest of the code is as follows

var gulp = require("gulp"),
    watch = require('gulp-watch');

gulp.task('default', function(done){
  console.log("You created the default task");
  done();``
});

gulp.task('html', function(done){
  console.log('modifying the html');
  done();
});

gulp.watch('watch', function() {
 watch('./app/index.html', function() {
  gulp.start('html');
 });
});

Solution

  • You don't need to convert your tasks to named functions - although that is considered best practice and is easy to do.

    To fix your watch task, try:

    gulp.watch('watch', function(done) {
     watch('./app/index.html', gulp.series('html'));
     done();  
    });
    

    To change to named functions:

    function html(done) {
      gulp.src(….)
        console.log('modifying the html');
        done();
    };
    
    function watch(done) {
     watch('./app/index.html', gulp.series('html'));
     done();  
    });
    
    exports.html= gulp.series(html);
    exports.default = gulp.series(watch);
    

    Note that now the watch task is not called as a string, i.e., 'watch', but just watch.

    In exports.html, the gulp.series is not strictly needed as there is only one task there so exports.html= html; is sufficient.

    And you only need to export a task if you wish to call it directly (as from the command line gulp html for example). If say the html task will only be called internally by other tasks then there is no need to export it.