Search code examples
javascriptgulpgulp-concatgulp-uglify

My gulp task to "concat" and "dest" my .css file, is only running if I run 2 times


The concatenation and destination to my public/assets/css is only working if i run 2 times the task. Even if I run just the app.css (npm run dev app.css), only work if I run twice.

const gulp = require('gulp')
const htmlmin = require('gulp-htmlmin')
const uglify = require('gulp-uglify')
const uglifycss = require('gulp-uglifycss')
const concat = require('gulp-concat')
const babel = require('gulp-babel')
const sass = require('gulp-sass')

gulp.task('app', ['app.html', 'app.sass', 'app.js', 'app.assets', 'app.css'])

gulp.task('app.html', function(){
    gulp.src(['app/**/*.html'])
        .pipe(htmlmin({ collapseWhitespace: true, removeComments: true}))
        .pipe(gulp.dest('public'))
})

gulp.task('app.sass', function () {
    gulp.src(['sass/main.scss'])
        .pipe(sass.sync().on('error', sass.logError))
        .pipe(gulp.dest('app/css'))
});

gulp.task('app.css', function(){
    gulp.src(['app/**/*.css'])
        .pipe(uglifycss({ "uglyComments": true}))
        .pipe(concat('app.min.css'))
        .pipe(gulp.dest('public/assets/css'))
})

gulp.task('app.js', function(){
    gulp.src(['app/**/*.js'])
        .pipe(babel({ presets: ['es2015'] }))
        .pipe(uglify())
        .pipe(concat('app.min.js'))
        .pipe(gulp.dest('public/assets/js'))
})

gulp.task('app.assets', function(){
    gulp.src(['assets/**/*.*'])
        .pipe(gulp.dest('public/assets'))

})

Solution

  • For gulp to respect the order of the task dependencies you defined, you need to tell it when the task is done.

    To do so, you need to return a stream, a promise, or call the task function callback parameter.

    Since your tasks are pretty basic, just returning the stream should be enough.

    gulp.task('app.sass', function () {
        return gulp.src(['sass/main.scss']) // notice the return here
            .pipe(sass.sync().on('error', sass.logError))
            .pipe(gulp.dest('app/css'));
    });
    
    // make the sass task a dependency of the CSS task
    gulp.task('app.css', ['app.sass'], function(){
        return gulp.src(['app/**/*.css']) // notice the return here
            .pipe(uglifycss({ "uglyComments": true}))
            .pipe(concat('app.min.css'))
            .pipe(gulp.dest('public/assets/css'));
    });
    

    Now you don't need the app.sass since it will run before app.css.

    gulp.task('app', ['app.html', 'app.js', 'app.assets', 'app.css'])