index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. const applySourceMap = require('vinyl-sourcemaps-apply');
  3. const CleanCSS = require('clean-css');
  4. const path = require('path');
  5. const PluginError = require('plugin-error');
  6. const through = require('through2');
  7. module.exports = function gulpCleanCSS(options, callback) {
  8. options = Object.assign(options || {});
  9. if (arguments.length === 1 && Object.prototype.toString.call(arguments[0]) === '[object Function]')
  10. callback = arguments[0];
  11. let 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. if (file.sourceMap)
  19. options.sourceMap = JSON.parse(JSON.stringify(file.sourceMap));
  20. let contents = file.contents ? file.contents.toString() : '';
  21. let pass = {[file.path]: {styles: contents}};
  22. if (!options.rebaseTo && options.rebase !== false) {
  23. options.rebaseTo = path.dirname(file.path);
  24. }
  25. new CleanCSS(options).minify(pass, function (errors, css) {
  26. if (errors)
  27. return cb(errors.join(' '));
  28. if (typeof callback === 'function') {
  29. let details = {
  30. 'stats': css.stats,
  31. 'errors': css.errors,
  32. 'warnings': css.warnings,
  33. 'path': file.path,
  34. 'name': file.path.split(file.base)[1]
  35. };
  36. if (css.sourceMap)
  37. details['sourceMap'] = css.sourceMap;
  38. callback(details);
  39. }
  40. file.contents = new Buffer(css.styles);
  41. if (css.sourceMap) {
  42. let map = JSON.parse(css.sourceMap);
  43. map.file = path.relative(file.base, file.path);
  44. map.sources = map.sources.map(function (src) {
  45. return path.relative(file.base, file.path)
  46. });
  47. applySourceMap(file, map);
  48. }
  49. cb(null, file);
  50. });
  51. };
  52. return through.obj(transform);
  53. };