javascript – Using gulp.series to run two tasks sequentially isn’t working as expected

First of all, I’m new to using Gulp.

I’m trying to create two tasks for CSS / SASS processing. First task needs to compile SASS into CSS (using gulp-sass spirit node-sass), and output the resulting files into assets/dist/css folder. This task is working like a charm.

The second task needs to use gulp-purgecss to traverse the resulting CSS files (from task 1) and remove unused CSS rules, outputting the clean CSS files into assets/dist/css/min folder. But, unfortunatelly, this task is not working as expected.

I’ve created a “css” task that triggers, with gulp.seriesmy two tasks in the expected order, but looks like the second task – purgecss – is started before the files are finished by the first task – SASS compiling -, so the clean CSS files does not appear on assets/dist/css/min folder.

For testing, I’ve ran the “css” task twice, and, on the second time, the assets/dist/css/min folder appears containing my clean CSS, but those are based on old CSS files (generated on first run of “css” task), not the “fresh” ones generated on the second time.

Here is the tasks I mentioned:

gulp.task("css:build", (done) => {
    gulp.src("./assets/src/scss/admin/admin.scss")
        .pipe(sass.sync({
            outputStyle: "compressed"
        }).on("error", sass.logError))
        .pipe(gulp.dest("./assets/dist/css"));
    
    gulp.src("./assets/src/scss/theme/theme.scss")
        .pipe(sass.sync({
            outputStyle: "compressed"
        }).on("error", sass.logError))
        .pipe(gulp.dest("./assets/dist/css"));

    done();
});

gulp.task("css:purge", (done) => {
    gulp.src("./assets/dist/css/theme.css")
        .pipe(purgecss({
            content: ['./**/*.php']
        }))
        .pipe(gulp.dest("./assets/dist/css/min"));

    done();
});

gulp.task("css:watch", (done) => {
    gulp.watch("./assets/src/scss/**/*.scss", gulp.series("css:build", "css:purge"));
    
    done();
});

gulp.task("css", gulp.series("css:build", "css:purge"));

My guess is that gulp.series isn’t working as expected, waiting the css:build to complete before starting css:purge.

Can someone help me with this? Thanks!

Leave a Comment