Search code examples
gulpgulp-sassgulp-imports

Create CSS file that @imports other CSS files using gulp


I have a gulp task to split a CSS file to multiple CSS files (because of the 4095 selectors limitation for IE 6-9) using gulp-sakugawa.

Original CSS:

app.css

Split CSS:

app_1.css
app_2.css
app_3.css
etc...

I need to @import these split files into a newly created CSS file style.css, something like below:

@import url('app_1.css');
@import url('app_2.css');
@import url('app_3.css');
//etc...

How can I do this in the following task?

gulp.task('splitCSS', function() {
  gulp.src(config.baseDir + '/assets/css/app.css')
    .pipe(gulpSakugawa({
       maxSelectors: 4000,
       mediaQueries: 'separate',
       suffix: '_'
    }))
    .pipe(gulp.dest(config.baseDir + '/assets/css/split'));
});

Solution

  • The following solution uses through2 to collect all the files in the stream and then emit a single file style.css that contains @import statements for all the files:

    var through2 = require('through2');
    var path = require('path');
    
    function createCssImports() {
      var lastFile, files = [];
      return through2.obj(function(file, enc, cb) {
        files.push(path.basename(file.path));
        cb(null, lastFile = file);
      }, function (cb) {
        var file = lastFile.clone();
        file.contents = new Buffer(files.map(function(f) {
          return "@import url('" + f + "');"
        }).join('\n'));
        file.path = path.join(path.dirname(file.path), 'style.css');
        this.push(file);
        cb();
      });
    }
    
    gulp.task('splitCss', function() {
      return gulp.src(config.baseDir + '/assets/css/app.css')
         .pipe(gulpSakugawa({
            maxSelectors: 4000,
            mediaQueries: 'separate',
            suffix: '_'
         }))
         .pipe(createCssImports())
         .pipe(gulp.dest(config.baseDir + '/assets/css/split'));
    });