index.js 2.26 KB
Newer Older
Nicolas Widart's avatar
Nicolas Widart committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
var path = require('path'),
  gutil = require('gulp-util'),
  CleanCSS  = require('clean-css'),
  through2 = require('through2'),
  BufferStreams = require('bufferstreams'),
  cache = require('memory-cache');

function objectIsEqual(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}

function minify(options, file, buffer) {
  var rawContents = String(buffer);
  var cached;
  if (options.cache &&
      (cached = cache.get(file.path)) &&
      cached.raw === rawContents &&
      objectIsEqual(cached.options, options)) {

      // cache hit
      css = cached.minified;

  } else {
    // cache miss or cache not enabled
    css = new CleanCSS(options).minify(rawContents);

    if (options.cache) {
      cache.put(file.path, {
        raw: rawContents,
        minified: css,
        options: options
      });
    }
  }
  return css;
}

// File level transform function
function minifyCSSTransform(opt, file) {

  // Return a callback function handling the buffered content
  return function(err, buf, cb) {

    // Handle any error
    if(err) cb(gutil.PluginError('minify-css', err));

    // Use the buffered content
    buf = Buffer(minify(opt, file, buf));

    // Bring it back to streams
    cb(null, buf);
  };
}

// Plugin function
function minifyCSSGulp(opt){
  if (!opt) opt = {};

  function modifyContents(file, enc, done){
    if(file.isNull()) {
      done(null, file);
      return;
    }

    if(file.isStream()) {
      file.contents = file.contents.pipe(new BufferStreams(minifyCSSTransform(opt, file)));
      done(null, file);
      return;
    }

    // Image URLs are rebased with the assumption that they are relative to the
    // CSS file they appear in (unless "relativeTo" option is explicitly set by
    // caller)
    var relativeToTmp = opt.relativeTo;
    opt.relativeTo = relativeToTmp || path.resolve(path.dirname(file.path));

    var newContents = minify(opt, file, file.contents);

    // Restore original "relativeTo" value
    opt.relativeTo = relativeToTmp;
    file.contents = new Buffer(newContents);

    done(null, file);
  }

  return through2.obj(modifyContents);
}

// Export the file level transform function for other plugins usage
minifyCSSGulp.fileTransform = minifyCSSTransform;

// Export the plugin main function
module.exports = minifyCSSGulp;