Gulp sass to css: combine selectors with same property/values

1.6k views Asked by At

I am trying to find any Gulp module that can combine css rules having same property/value. Following example demonstrates my problem.

h2 {
  font-size: 14px;
}
p {
   font-size: 14px;
}

Output should be

h2, p {
  font-size: 14px;
}

It would be great if there's way to solve this issue while compiling scss to css. Thanks in advance

1

There are 1 answers

3
Ciarán Tobin On BEST ANSWER

You can use gulp-clean-css. For example, this will compile index.scss to build/index.css given the output you asked for:

const gulp = require('gulp');
const sass = require('gulp-sass');
const cleanCss = require('gulp-clean-css');

gulp.task('default', function () {
    return gulp.src('index.scss')
        .pipe(sass())
        .pipe(cleanCss({ level: 2 }))
        .pipe(gulp.dest('build'));
});

gulp-clean-css uses clean-css, where merging the selectors like this is considered a "level 2 optimisation", which is why I set the level as an option above. You can look at those options for more details.


Update

In response to the comment below, you can use more aggressive merging:

gulp.task('default', function () {
    return gulp.src('index.scss')
        .pipe(sass())
        .pipe(cleanCss({ level: { 2: { restructureRules: true } } }))
        .pipe(gulp.dest('build'));
});

Before (index.scss):

@for $i from 1 through 3 {
    .grid-#{$i} {
        width: 30px;
        background-color: blue;
        font-size: 30px;
        height: $i * 10px;
    }
}

After (index.css):

.grid-1,.grid-2,.grid-3{width:30px;background-color:#00f;font-size:30px}
.grid-1{height:10px}
.grid-2{height:20px}
.grid-3{height:30px}