Search code examples
gulp

I'm trying to fix a reference error when using Gulp 4, It won't watch my sass nor show the changes in the browser


I can't seem to figure out what the error is talking about. I set up everything else correctly but none of it works because of the error. And I can't seem to find this exact problem anywhere. Any help would be appreciated.

I keep getting this error.

ReferenceError: watchFiles is not defined
    at Object.<anonymous> (gulpfile.js:42:29)

The specific code that the error is pointing to.

const watch = gulp.parallel(watchFiles, initBrowsersync);

the code above the error for context

function initBrowsersync(done) {
    browserSync.init({
        server: {
            baseDir: 'app',
            index: 'index.html'
        },
        startPath: '/html'
    });

    done();
}

gulp.task('watchFiles', () => {
    gulp.watch('app/scss/**/*.scss', gulp.series('style'));
    gulp.watch('app/**/*.html').on('change', browserSync.reload);
    gulp.watch('app/css/*.css').on('change', browserSync.reload);
    gulp.watch('app/javascript/**/*.js').on('change', browserSync.reload);
});

The code below the error for context

exports.style = style;
exports.watch = watchFiles;
exports.default = watch;

and just below that are the other tasks I set it to run like uglify and minify-css.


Solution

  • Change

    const watch = gulp.parallel(watchFiles, initBrowsersync);

    to

    const watch = gulp.parallel('watchFiles', initBrowsersync);

    When using the gulp.task('watchFiles',... way of defining tasks, then your other references to that task must be as a string.

    When using the function initBrowsersync(done) { define a function version than you can refer to those tasks as a simple non-string function reference.

    So your other option is to define watchFiles like so:

    //gulp.task('watchFiles', () => {
    
    function watchFiles() {
      gulp.watch('app/scss/**/*.scss', gulp.series('style'));
      gulp.watch('app/**/*.html').on('change', browserSync.reload);
      gulp.watch('app/css/*.css').on('change', browserSync.reload);
      gulp.watch('app/javascript/**/*.js').on('change', browserSync.reload);
    //});
    };
    

    and then you could use:

    const watch = gulp.parallel(watchFiles, initBrowsersync);

    I suggest this second approach.