index.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 'use strict';
  2. var through = require('through2'),
  3. uglify = require('uglify-js'),
  4. merge = require('deepmerge'),
  5. PluginError = require('gulp-util/lib/PluginError'),
  6. applySourceMap = require('vinyl-sourcemaps-apply'),
  7. reSourceMapComment = /\n\/\/# sourceMappingURL=.+?$/,
  8. pluginName = 'gulp-uglify';
  9. function minify(file, options) {
  10. var mangled;
  11. try {
  12. mangled = uglify.minify(String(file.contents), options);
  13. mangled.code = new Buffer(mangled.code.replace(reSourceMapComment, ''));
  14. return mangled;
  15. } catch (e) {
  16. return createError(file, e);
  17. }
  18. }
  19. function setup(opts) {
  20. var options = merge(opts || {}, {
  21. fromString: true,
  22. output: {}
  23. });
  24. if (options.preserveComments === 'all') {
  25. options.output.comments = true;
  26. } else if (options.preserveComments === 'some') {
  27. // preserve comments with directives or that start with a bang (!)
  28. options.output.comments = /^!|@preserve|@license|@cc_on/i;
  29. } else if (typeof options.preserveComments === 'function') {
  30. options.output.comments = options.preserveComments;
  31. }
  32. return options;
  33. }
  34. function createError(file, err) {
  35. if (typeof err === 'string') {
  36. return new PluginError(pluginName, file.path + ': ' + err, {
  37. fileName: file.path,
  38. showStack: false
  39. });
  40. }
  41. var msg = err.message || err.msg || /* istanbul ignore next */ 'unspecified error';
  42. return new PluginError(pluginName, file.path + ': ' + msg, {
  43. fileName: file.path,
  44. lineNumber: err.line,
  45. stack: err.stack,
  46. showStack: false
  47. });
  48. }
  49. module.exports = function(opt) {
  50. function uglify(file, encoding, callback) {
  51. var options = setup(opt);
  52. if (file.isNull()) {
  53. return callback(null, file);
  54. }
  55. if (file.isStream()) {
  56. return callback(createError(file, 'Streaming not supported'));
  57. }
  58. if (file.sourceMap) {
  59. options.outSourceMap = file.relative;
  60. options.inSourceMap = file.sourceMap.mappings !== '' ? file.sourceMap : undefined;
  61. }
  62. var mangled = minify(file, options);
  63. if (mangled instanceof PluginError) {
  64. return callback(mangled);
  65. }
  66. file.contents = mangled.code;
  67. if (file.sourceMap) {
  68. applySourceMap(file, mangled.map);
  69. }
  70. callback(null, file);
  71. }
  72. return through.obj(uglify);
  73. };