You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. const { extname } = require('path');
  3. const through2 = require('through2-concurrent');
  4. const PluginError = require('plugin-error');
  5. const colors = require('ansi-colors');
  6. const fancyLog = require('fancy-log');
  7. const filesize = require('filesize');
  8. const { round10 } = require('round10');
  9. const optimize = require('./optimize');
  10. const SUPPORTED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.svg'];
  11. const NOOP = () => {};
  12. module.exports = options => through2.obj({
  13. maxConcurrency: options ? options.concurrent : null
  14. }, (file, enc, callback) => {
  15. if (file.isNull()) {
  16. return callback(null, file);
  17. }
  18. if (file.isStream()) {
  19. return callback(new Error('gulp-image: Streaming is not supported'));
  20. }
  21. const log = options && options.quiet ? NOOP : fancyLog;
  22. const extension = extname(file.path).toLowerCase();
  23. if (!SUPPORTED_EXTENSIONS.includes(extension)) {
  24. log('gulp-image: Skipping unsupported image ' + colors.blue(file.relative));
  25. return callback(null, file);
  26. }
  27. optimize(file.contents, Object.assign({
  28. pngquant : true,
  29. optipng : false,
  30. zopflipng : true,
  31. jpegRecompress : false,
  32. mozjpeg : true,
  33. guetzli : false,
  34. gifsicle : true,
  35. svgo : true
  36. }, options)).then(buffer => {
  37. const before = file.contents.length;
  38. const after = buffer.length;
  39. const diff = before - after;
  40. const diffPercent = round10(100 * (diff / before), -1);
  41. if (diff <= 0) {
  42. log(
  43. colors.green('- ') + file.relative + colors.gray(' ->') +
  44. colors.gray(' Cannot improve upon ') + colors.cyan(filesize(before))
  45. );
  46. } else {
  47. file.contents = buffer;
  48. log(
  49. colors.green('✔ ') + file.relative + colors.gray(' ->') +
  50. colors.gray(' before=') + colors.yellow(filesize(before)) +
  51. colors.gray(' after=') + colors.cyan(filesize(after)) +
  52. colors.gray(' reduced=') + colors.green(filesize(diff) + '(' + diffPercent + '%)')
  53. );
  54. }
  55. callback(null, file);
  56. }).catch(error => {
  57. callback(new PluginError('gulp-image', error));
  58. });
  59. });