minifier.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict';
  2. var through = require('through2');
  3. var deap = require('deap');
  4. var PluginError = require('gulp-util/lib/PluginError');
  5. var log = require('fancy-log');
  6. var applySourceMap = require('vinyl-sourcemaps-apply');
  7. var saveLicense = require('uglify-save-license');
  8. var isObject = require('isobject');
  9. var createError = require('./lib/create-error');
  10. var reSourceMapComment = /\n\/\/# sourceMappingURL=.+?$/;
  11. function trycatch(fn, handle) {
  12. try {
  13. return fn();
  14. } catch (err) {
  15. return handle(err);
  16. }
  17. }
  18. function setup(opts) {
  19. if (opts && !isObject(opts)) {
  20. log('gulp-uglify expects an object, non-object provided');
  21. opts = {};
  22. }
  23. var options = deap({}, opts, {
  24. fromString: true,
  25. output: {}
  26. });
  27. if (options.preserveComments === 'all') {
  28. options.output.comments = true;
  29. } else if (options.preserveComments === 'some') {
  30. // preserve comments with directives or that start with a bang (!)
  31. options.output.comments = /^!|@preserve|@license|@cc_on/i;
  32. } else if (options.preserveComments === 'license') {
  33. options.output.comments = saveLicense;
  34. } else if (typeof options.preserveComments === 'function') {
  35. options.output.comments = options.preserveComments;
  36. }
  37. return options;
  38. }
  39. module.exports = function (opts, uglify) {
  40. function minify(file, encoding, callback) {
  41. var options = setup(opts || {});
  42. if (file.isNull()) {
  43. return callback(null, file);
  44. }
  45. if (file.isStream()) {
  46. return callback(createError(file, 'Streaming not supported'));
  47. }
  48. if (file.sourceMap) {
  49. options.outSourceMap = file.relative;
  50. }
  51. var originalContents = String(file.contents);
  52. var mangled = trycatch(function () {
  53. var m = uglify.minify(String(file.contents), options);
  54. m.code = new Buffer(m.code.replace(reSourceMapComment, ''));
  55. return m;
  56. }, createError.bind(null, file));
  57. if (mangled instanceof PluginError) {
  58. return callback(mangled);
  59. }
  60. file.contents = mangled.code;
  61. if (file.sourceMap) {
  62. var sourceMap = JSON.parse(mangled.map);
  63. sourceMap.sources = [file.relative];
  64. sourceMap.sourcesContent = [originalContents];
  65. applySourceMap(file, sourceMap);
  66. }
  67. callback(null, file);
  68. }
  69. return through.obj(minify);
  70. };