index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const applySourceMap = require('vinyl-sourcemaps-apply');
  2. const CleanCSS = require('clean-css');
  3. const path = require('path');
  4. const PluginError = require('plugin-error');
  5. const through = require('through2');
  6. module.exports = (options, callback) => {
  7. let _callback = callback || (o => undefined);
  8. return through.obj(function (file, enc, cb) {
  9. let _options = Object.assign({}, options || {});
  10. if (file.isNull()) {
  11. return cb(null, file);
  12. }
  13. if (file.isStream()) {
  14. this.emit('error', new PluginError('gulp-clean-css', 'Streaming not supported!'));
  15. return cb(null, file);
  16. }
  17. if (file.sourceMap) {
  18. _options.sourceMap = JSON.parse(JSON.stringify(file.sourceMap));
  19. }
  20. const content = {
  21. [file.path]: {styles: file.contents ? file.contents.toString() : ''}
  22. };
  23. if (!_options.rebaseTo && _options.rebase !== false) {
  24. _options.rebaseTo = path.dirname(file.path);
  25. }
  26. new CleanCSS(_options).minify(content, (errors, css) => {
  27. if (errors) {
  28. return cb(errors.join(' '));
  29. }
  30. let details = {
  31. 'stats': css.stats,
  32. 'errors': css.errors,
  33. 'warnings': css.warnings,
  34. 'path': file.path,
  35. 'name': file.path.split(file.base)[1]
  36. };
  37. if (css.sourceMap) {
  38. details['sourceMap'] = css.sourceMap;
  39. }
  40. _callback(details);
  41. file.contents = new Buffer.from(css.styles);
  42. if (css.sourceMap) {
  43. const iMap = JSON.parse(css.sourceMap);
  44. const oMap = Object.assign({}, iMap, {
  45. file: path.relative(file.base, file.path),
  46. sources: iMap.sources.map(mapSrc => path.relative(file.base, mapSrc))
  47. });
  48. applySourceMap(file, oMap);
  49. }
  50. cb(null, file);
  51. });
  52. });
  53. };