index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const applySourceMap = require('vinyl-sourcemaps-apply');
  2. const CleanCSS = require('clean-css');
  3. const objectAssign = require('object-assign');
  4. const path = require('path');
  5. const PluginError = require('gulp-util').PluginError;
  6. const through = require('through2');
  7. module.exports = function gulpCleanCSS(options, callback) {
  8. options = options || {};
  9. if (arguments.length === 1 && Object.prototype.toString.call(arguments[0]) === '[object Function]')
  10. callback = arguments[0];
  11. var transform = function (file, enc, cb) {
  12. if (!file || !file.contents)
  13. return cb(null, file);
  14. if (file.isStream()) {
  15. this.emit('error', new PluginError('gulp-clean-css', 'Streaming not supported!'));
  16. return cb(null, file);
  17. }
  18. var fileOptions = objectAssign({target: file.path}, options);
  19. if (!fileOptions.relativeTo && file.path)
  20. fileOptions.relativeTo = path.dirname(path.resolve(file.path));
  21. if (file.sourceMap)
  22. fileOptions.sourceMap = JSON.parse(JSON.stringify(file.sourceMap));
  23. var style = file.contents ? file.contents.toString() : '';
  24. new CleanCSS(fileOptions).minify(style, function (errors, css) {
  25. if (errors)
  26. return cb(errors.join(' '));
  27. if (typeof callback === 'function') {
  28. var details = {
  29. 'stats': css.stats,
  30. 'errors': css.errors,
  31. 'warnings': css.warnings,
  32. 'path': file.path,
  33. 'name': file.path.split(file.base)[1]
  34. }
  35. if (css.sourceMap)
  36. details['sourceMap'] = css.sourceMap;
  37. callback(details);
  38. }
  39. file.contents = new Buffer(css.styles);
  40. if (css.sourceMap) {
  41. var map = JSON.parse(css.sourceMap);
  42. map.file = path.relative(file.base, file.path);
  43. map.sources = map.sources.map(function (src) {
  44. return path.relative(file.base, file.path)
  45. });
  46. applySourceMap(file, map);
  47. }
  48. cb(null, file);
  49. });
  50. };
  51. return through.obj(transform);
  52. };