index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. const gutil = require('gulp-util');
  3. const through = require('through2');
  4. const applySourceMap = require('vinyl-sourcemaps-apply');
  5. const autoprefixer = require('autoprefixer');
  6. const postcss = require('postcss');
  7. module.exports = opts => {
  8. return through.obj((file, enc, cb) => {
  9. if (file.isNull()) {
  10. cb(null, file);
  11. return;
  12. }
  13. if (file.isStream()) {
  14. cb(new gutil.PluginError('gulp-autoprefixer', 'Streaming not supported'));
  15. return;
  16. }
  17. postcss(autoprefixer(opts)).process(file.contents.toString(), {
  18. map: file.sourceMap ? {annotation: false} : false,
  19. from: file.path,
  20. to: file.path
  21. }).then(res => {
  22. file.contents = Buffer.from(res.css);
  23. if (res.map && file.sourceMap) {
  24. applySourceMap(file, res.map.toString());
  25. }
  26. const warnings = res.warnings();
  27. if (warnings.length > 0) {
  28. gutil.log('gulp-autoprefixer:', '\n ' + warnings.join('\n '));
  29. }
  30. setImmediate(cb, null, file);
  31. }).catch(err => {
  32. const cssError = err.name === 'CssSyntaxError';
  33. if (cssError) {
  34. err.message += err.showSourceCode();
  35. }
  36. // Prevent stream unhandled exception from being suppressed by Promise
  37. setImmediate(cb, new gutil.PluginError('gulp-autoprefixer', err, {
  38. fileName: file.path,
  39. showStack: !cssError
  40. }));
  41. });
  42. });
  43. };