index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. var gutil = require('gulp-util');
  3. var through = require('through2');
  4. var applySourceMap = require('vinyl-sourcemaps-apply');
  5. var autoprefixer = require('autoprefixer');
  6. var postcss = require('postcss');
  7. module.exports = function (opts) {
  8. return through.obj(function (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(function (res) {
  22. file.contents = new Buffer(res.css);
  23. if (res.map && file.sourceMap) {
  24. applySourceMap(file, res.map.toString());
  25. }
  26. var 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(function (err) {
  32. var 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. };