gulp duplicating tasks in the terminal

109 views Asked by At

I have a problem with my gulp, I don't know how to explain it, but you will understand the problem when you see it, basically, I think my gulp is duplicating the task and therefore the execution can take a while, but if I finish the gulp and execute it again, the problem does not happen the first time it is compiled, but over time it is repeated more and more (first doubles, then 4x, 8x and so on)

my gulp:

    var gulp = require('gulp'),
    //Js
    babel = require('gulp-babel');
    uglify = require('gulp-uglify'),
    filesJs = './js/edit/*.js',
    outputJs = './js',
    //Sass
    sass = require('gulp-sass'),
    filesCss = './css/**/*.+(scss|sass)',
    outputCss = './css';
const {
    watch
} = require('gulp');

//Uglify
gulp.task('uglify', function () {
    gulp.src(filesJs)
        .pipe(babel({presets: ['@babel/preset-env']}))
        .pipe(uglify())
        .pipe(gulp.dest(outputJs));
});

const watcherJS = watch([filesJs]);
watcherJS.on('change', function (path, stats) {
    console.log(`File ${path} was changed`);
    return gulp.watch(filesJs, gulp.series('uglify'));
});

//Sass
gulp.task('sass', function () {
    return gulp.src(filesCss)
        .pipe(sass({
            outputStyle: 'compressed'
        }).on('error', sass.logError))
        .pipe(gulp.dest(outputCss));
});

const watcherCSS = watch([filesCss]);
watcherCSS.on('change', function (path, stats) {
    console.log(`File ${path} was changed`);
    return gulp.watch(filesCss, gulp.series('sass'));
});

//Run/Watch
gulp.task('default', gulp.parallel('uglify', 'sass'));

my terminal after a save the .sass file once

File css\style.sass was changed
[09:43:18] Starting 'sass'...
[09:43:18] Starting 'sass'...
[09:43:18] Starting 'sass'...
[09:43:18] Starting 'sass'...
[09:43:33] Finished 'sass' after 15 s
[09:43:33] Finished 'sass' after 15 s
[09:43:33] Finished 'sass' after 15 s
[09:43:33] Finished 'sass' after 15 s
1

There are 1 answers

0
Mark On BEST ANSWER

It is almost certainly your use of the chokidar watch functionality. Your code won't even run for me. And you don't need that complexity. I suggest getting rid of

const watcherJS = watch([filesJs]);
watcherJS.on('change', function (path, stats) {
    console.log(`File ${path} was changed`);
    return gulp.watch(filesJs, gulp.series('uglify'));  // this is very strange, must be wrong
});

const watcherCSS = watch([filesCss]);
watcherCSS.on('change', function (path, stats) {
    console.log(`File ${path} was changed`);
    return gulp.watch(filesCss, gulp.series('sass'));
});

and replacing with:

gulp.task('watchFiles', function () {
    gulp.watch(filesCss, gulp.series('sass'));
    gulp.watch(filesJs, gulp.series('uglify'));
});

and using

gulp.task('default', gulp.series('uglify', 'sass', 'watchFiles'));