1

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

Anwer AR
  • 155
  • 1
  • 16

1 Answers1

3

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}
Ciarán Tobin
  • 7,306
  • 1
  • 29
  • 45
  • Thank you @MadScone it worked normally for me. but i am using Sass loop to print calculated girds width into different cols and this method does not merge those columns with same width. also i try to minify .css file with `level 2' optimizations but surprisingly that does not work too. any idea? – Anwer AR Sep 04 '17 at 15:34
  • You can play around with the `clean-css` options to get what you want. Please see my edit above. I'm not sure exactly why you're doing this by the way. It can be slightly dangerous to restructure your CSS like this because you may change things unexpectedly when rearranging the order of how things are defined. – Ciarán Tobin Sep 04 '17 at 15:58
  • Thank you very much Sir. you saved my day. i was trying to figure it out from yesterday. `level: { 2: { restructureRules: true, mergeSemantically: true } }` perfectly works for me. – Anwer AR Sep 04 '17 at 16:39