index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 = opts => {
  9. return through.obj((file, enc, cb) => {
  10. if (file.isNull()) {
  11. cb(null, file);
  12. return;
  13. }
  14. if (file.isStream()) {
  15. cb(new PluginError('gulp-autoprefixer', 'Streaming not supported'));
  16. return;
  17. }
  18. postcss(autoprefixer(opts)).process(file.contents.toString(), {
  19. map: file.sourceMap ? {annotation: false} : false,
  20. from: file.path,
  21. to: file.path
  22. }).then(res => {
  23. file.contents = Buffer.from(res.css);
  24. if (res.map && file.sourceMap) {
  25. const map = res.map.toJSON();
  26. map.file = file.relative;
  27. map.sources = map.sources.map(() => file.relative);
  28. applySourceMap(file, map);
  29. }
  30. const warnings = res.warnings();
  31. if (warnings.length > 0) {
  32. fancyLog('gulp-autoprefixer:', '\n ' + warnings.join('\n '));
  33. }
  34. setImmediate(cb, null, file);
  35. }).catch(error => {
  36. const cssError = error.name === 'CssSyntaxError';
  37. if (cssError) {
  38. error.message += error.showSourceCode();
  39. }
  40. // Prevent stream unhandled exception from being suppressed by Promise
  41. setImmediate(cb, new PluginError('gulp-autoprefixer', error, {
  42. fileName: file.path,
  43. showStack: !cssError
  44. }));
  45. });
  46. });
  47. };