index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict';
  2. const fancyLog = require('fancy-log');
  3. const PluginError = require('plugin-error');
  4. const through = require('through2');
  5. const applySourceMap = require('vinyl-sourcemaps-apply');
  6. const autoprefixer = require('autoprefixer');
  7. const postcss = require('postcss');
  8. module.exports = options => {
  9. return through.obj((file, encoding, callback) => {
  10. if (file.isNull()) {
  11. callback(null, file);
  12. return;
  13. }
  14. if (file.isStream()) {
  15. callback(new PluginError('gulp-autoprefixer', 'Streaming not supported'));
  16. return;
  17. }
  18. (async () => {
  19. try {
  20. const result = await postcss(autoprefixer(options)).process(file.contents.toString(), {
  21. map: file.sourceMap ? {annotation: false} : false,
  22. from: file.path,
  23. to: file.path
  24. });
  25. file.contents = Buffer.from(result.css);
  26. if (result.map && file.sourceMap) {
  27. const map = result.map.toJSON();
  28. map.file = file.relative;
  29. map.sources = map.sources.map(() => file.relative);
  30. applySourceMap(file, map);
  31. }
  32. const warnings = result.warnings();
  33. if (warnings.length > 0) {
  34. fancyLog('gulp-autoprefixer:', '\n ' + warnings.join('\n '));
  35. }
  36. setImmediate(callback, null, file);
  37. } catch (error) {
  38. const cssError = error.name === 'CssSyntaxError';
  39. if (cssError) {
  40. error.message += error.showSourceCode();
  41. }
  42. // Prevent stream unhandled exception from being suppressed by Promise
  43. setImmediate(callback, new PluginError('gulp-autoprefixer', error, {
  44. fileName: file.path,
  45. showStack: !cssError
  46. }));
  47. }
  48. })();
  49. });
  50. };