minify.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. var Buffer = require('safe-buffer').Buffer;
  3. var applySourceMap = require('vinyl-sourcemaps-apply');
  4. var isObject = require('isobject');
  5. var extend = require('extend-shallow');
  6. var createError = require('./create-error');
  7. module.exports = function(uglify, log) {
  8. function setup(opts) {
  9. if (opts && !isObject(opts)) {
  10. log.warn('gulp-uglify expects an object, non-object provided');
  11. opts = {};
  12. }
  13. return extend(
  14. {},
  15. {
  16. output: {}
  17. },
  18. opts
  19. );
  20. }
  21. return function(opts) {
  22. return function(file) {
  23. var options = setup(opts || {});
  24. var hasSourceMaps = Boolean(file.sourceMap);
  25. if (file.isNull()) {
  26. return file;
  27. }
  28. if (file.isStream()) {
  29. throw createError(file, 'Streaming not supported', null);
  30. }
  31. if (hasSourceMaps) {
  32. options.sourceMap = {
  33. filename: file.sourceMap.file,
  34. includeSources: true
  35. };
  36. // UglifyJS generates broken source maps if the input source map
  37. // does not contain mappings.
  38. if (file.sourceMap.mappings) {
  39. options.sourceMap.content = file.sourceMap;
  40. }
  41. }
  42. var fileMap = {};
  43. fileMap[file.relative] = String(file.contents);
  44. var mangled = uglify.minify(fileMap, options);
  45. if (!mangled || mangled.error) {
  46. throw createError(
  47. file,
  48. 'unable to minify JavaScript',
  49. mangled && mangled.error
  50. );
  51. }
  52. if (mangled.warnings) {
  53. mangled.warnings.forEach(function(warning) {
  54. log.warn('gulp-uglify [%s]: %s', file.relative, warning);
  55. });
  56. }
  57. file.contents = Buffer.from(mangled.code);
  58. if (hasSourceMaps) {
  59. var sourceMap = JSON.parse(mangled.map);
  60. applySourceMap(file, sourceMap);
  61. }
  62. return file;
  63. };
  64. };
  65. };