Search code examples
gulpgulp-sassevent-stream

gulp task to merge generated sass event stream as required order is not working


I have three bootstrap sass and two more sass files which I am compiling and merging into one css. On bootstrap I am running "uncss" to get rid of unused css however for others I am not running the "uncss" as I don't want. To merge these I am using "eventstream". Unfortunately the order of generated combined css files is not as per my requirement. No matter what, bootstrap css files are always printing at the last which is causing issue. Following is my gulp task

var eventStream = require('event-stream'),
        sass = require('gulp-sass'),
        uncss = require('gulp-uncss'),
        csso = require('gulp-csso'),
        concat = require('gulp-concat');

gulp.task('sass', function () {
    //Copy bootstrap fonts files
    gulp.src(config.sassPath + '/vendor/bootstrap-sass-3.3.2/assets/fonts/**/*')
            .pipe(gulp.dest(config.cssPath + '/fonts'));


    //compile bootstrap css, compress and remove unused css rules
    var bootstrapCss = gulp.src(config.sassPath + '/vendor/custom/custom-bootstrap.scss')
            .pipe(sass({outputStyle: 'compressed'}))
            .pipe(uncss({
                html: ['./application/public/templates/**/*.html']
            }))
            .pipe(csso());

    //Compile slick css file to compress it
    var slickCss = gulp.src(config.sassPath + '/vendor/slick/slick.scss')
            .pipe(sass({outputStyle: 'compressed'}));

    //Compile mysite css file and compress it
    var mysiteCss = gulp.src(config.sassPath + '/application/my-site.scss')
            .pipe(sass({outputStyle: 'compressed'}));

    //merge all css
    eventStream.merge(slickCss, mysiteCss, bootstrapCss)
            .pipe(concat('my-final-site.css'))
            .pipe(gulp.dest(config.cssPath + '/stylesheets'));

});

In the final generated my-final-site.css, css are printing as below order

1. slick
2. my-site
3. bootstrap 

I want to keep bootstrap at top so that my customized bootstrap code cane work.

Please help.


Solution

  • you can write custom-comparator like this

    // sort with a custom comparator 
    gulp.src('./src/js/**/*.js')
    .pipe(sort({
        comparator: function(file1, file2) {
            if (file1.path.indexOf('build') > -1) {
                return 1;
            }
            if (file2.path.indexOf('build') > -1) {
                return -1;
            }
            return 0;
        }
    }))
    .pipe(gulp.dest('./build/js'));
    

    read more about it here