index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  7. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  8. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9. var SourceMapConsumer = require("source-map").SourceMapConsumer;
  10. var SourceMapSource = require("webpack-sources").SourceMapSource;
  11. var RawSource = require("webpack-sources").RawSource;
  12. var ConcatSource = require("webpack-sources").ConcatSource;
  13. var RequestShortener = require("webpack/lib/RequestShortener");
  14. var ModuleFilenameHelpers = require("webpack/lib/ModuleFilenameHelpers");
  15. var uglify = require("uglify-js");
  16. var UglifyJsPlugin = function () {
  17. function UglifyJsPlugin(options) {
  18. _classCallCheck(this, UglifyJsPlugin);
  19. if ((typeof options === "undefined" ? "undefined" : _typeof(options)) !== "object" || Array.isArray(options)) options = {};
  20. if (typeof options.compressor !== "undefined") options.compress = options.compressor;
  21. this.options = options;
  22. }
  23. _createClass(UglifyJsPlugin, [{
  24. key: "apply",
  25. value: function apply(compiler) {
  26. var options = this.options;
  27. options.test = options.test || /\.js($|\?)/i;
  28. var warningsFilter = options.warningsFilter || function () {
  29. return true;
  30. };
  31. var requestShortener = new RequestShortener(compiler.context);
  32. compiler.plugin("compilation", function (compilation) {
  33. if (options.sourceMap) {
  34. compilation.plugin("build-module", function (module) {
  35. // to get detailed location info about errors
  36. module.useSourceMap = true;
  37. });
  38. }
  39. compilation.plugin("optimize-chunk-assets", function (chunks, callback) {
  40. var files = [];
  41. chunks.forEach(function (chunk) {
  42. return files.push.apply(files, chunk.files);
  43. });
  44. files.push.apply(files, compilation.additionalChunkAssets);
  45. var filteredFiles = files.filter(ModuleFilenameHelpers.matchObject.bind(undefined, options));
  46. filteredFiles.forEach(function (file) {
  47. var oldWarnFunction = uglify.AST_Node.warn_function;
  48. var warnings = [];
  49. var sourceMap = void 0;
  50. try {
  51. var asset = compilation.assets[file];
  52. if (asset.__UglifyJsPlugin) {
  53. compilation.assets[file] = asset.__UglifyJsPlugin;
  54. return;
  55. }
  56. var input = void 0;
  57. var inputSourceMap = void 0;
  58. if (options.sourceMap) {
  59. if (asset.sourceAndMap) {
  60. var sourceAndMap = asset.sourceAndMap();
  61. inputSourceMap = sourceAndMap.map;
  62. input = sourceAndMap.source;
  63. } else {
  64. inputSourceMap = asset.map();
  65. input = asset.source();
  66. }
  67. sourceMap = new SourceMapConsumer(inputSourceMap);
  68. uglify.AST_Node.warn_function = function (warning) {
  69. // eslint-disable-line camelcase
  70. var match = /\[.+:([0-9]+),([0-9]+)\]/.exec(warning);
  71. var line = +match[1];
  72. var column = +match[2];
  73. var original = sourceMap.originalPositionFor({
  74. line: line,
  75. column: column
  76. });
  77. if (!original || !original.source || original.source === file) return;
  78. if (!warningsFilter(original.source)) return;
  79. warnings.push(warning.replace(/\[.+:([0-9]+),([0-9]+)\]/, "") + "[" + requestShortener.shorten(original.source) + ":" + original.line + "," + original.column + "]");
  80. };
  81. } else {
  82. input = asset.source();
  83. uglify.AST_Node.warn_function = function (warning) {
  84. // eslint-disable-line camelcase
  85. warnings.push(warning);
  86. };
  87. }
  88. uglify.base54.reset();
  89. var ast = uglify.parse(input, {
  90. filename: file
  91. });
  92. if (options.compress !== false) {
  93. ast.figure_out_scope();
  94. var compress = uglify.Compressor(options.compress || {
  95. warnings: false
  96. }); // eslint-disable-line new-cap
  97. ast = compress.compress(ast);
  98. }
  99. if (options.mangle !== false) {
  100. ast.figure_out_scope(options.mangle || {});
  101. ast.compute_char_frequency(options.mangle || {});
  102. ast.mangle_names(options.mangle || {});
  103. if (options.mangle && options.mangle.props) {
  104. uglify.mangle_properties(ast, options.mangle.props);
  105. }
  106. }
  107. var output = {};
  108. output.comments = Object.prototype.hasOwnProperty.call(options, "comments") ? options.comments : /^\**!|@preserve|@license/;
  109. output.beautify = options.beautify;
  110. for (var k in options.output) {
  111. output[k] = options.output[k];
  112. }
  113. var extractedComments = [];
  114. if (options.extractComments) {
  115. var condition = {};
  116. if (typeof options.extractComments === "string" || options.extractComments instanceof RegExp) {
  117. // extractComments specifies the extract condition and output.comments specifies the preserve condition
  118. condition.preserve = output.comments;
  119. condition.extract = options.extractComments;
  120. } else if (Object.prototype.hasOwnProperty.call(options.extractComments, "condition")) {
  121. // Extract condition is given in extractComments.condition
  122. condition.preserve = output.comments;
  123. condition.extract = options.extractComments.condition;
  124. } else {
  125. // No extract condition is given. Extract comments that match output.comments instead of preserving them
  126. condition.preserve = false;
  127. condition.extract = output.comments;
  128. }
  129. // Ensure that both conditions are functions
  130. ["preserve", "extract"].forEach(function (key) {
  131. switch (_typeof(condition[key])) {
  132. case "boolean":
  133. var b = condition[key];
  134. condition[key] = function () {
  135. return b;
  136. };
  137. break;
  138. case "function":
  139. break;
  140. case "string":
  141. if (condition[key] === "all") {
  142. condition[key] = function () {
  143. return true;
  144. };
  145. break;
  146. }
  147. var regex = new RegExp(condition[key]);
  148. condition[key] = function (astNode, comment) {
  149. return regex.test(comment.value);
  150. };
  151. break;
  152. default:
  153. regex = condition[key];
  154. condition[key] = function (astNode, comment) {
  155. return regex.test(comment.value);
  156. };
  157. }
  158. });
  159. // Redefine the comments function to extract and preserve
  160. // comments according to the two conditions
  161. output.comments = function (astNode, comment) {
  162. if (condition.extract(astNode, comment)) {
  163. extractedComments.push(comment.type === "comment2" ? "/*" + comment.value + "*/" : "//" + comment.value);
  164. }
  165. return condition.preserve(astNode, comment);
  166. };
  167. }
  168. var map = void 0;
  169. if (options.sourceMap) {
  170. map = uglify.SourceMap({ // eslint-disable-line new-cap
  171. file: file,
  172. root: ""
  173. });
  174. output.source_map = map; // eslint-disable-line camelcase
  175. }
  176. var stream = uglify.OutputStream(output); // eslint-disable-line new-cap
  177. ast.print(stream);
  178. if (map) map = map + "";
  179. var stringifiedStream = stream + "";
  180. var outputSource = map ? new SourceMapSource(stringifiedStream, file, JSON.parse(map), input, inputSourceMap) : new RawSource(stringifiedStream);
  181. if (extractedComments.length > 0) {
  182. var commentsFile = options.extractComments.filename || file + ".LICENSE";
  183. if (typeof commentsFile === "function") {
  184. commentsFile = commentsFile(file);
  185. }
  186. // Write extracted comments to commentsFile
  187. var commentsSource = new RawSource(extractedComments.join("\n\n") + "\n");
  188. if (commentsFile in compilation.assets) {
  189. // commentsFile already exists, append new comments...
  190. if (compilation.assets[commentsFile] instanceof ConcatSource) {
  191. compilation.assets[commentsFile].add("\n");
  192. compilation.assets[commentsFile].add(commentsSource);
  193. } else {
  194. compilation.assets[commentsFile] = new ConcatSource(compilation.assets[commentsFile], "\n", commentsSource);
  195. }
  196. } else {
  197. compilation.assets[commentsFile] = commentsSource;
  198. }
  199. // Add a banner to the original file
  200. if (options.extractComments.banner !== false) {
  201. var banner = options.extractComments.banner || "For license information please see " + commentsFile;
  202. if (typeof banner === "function") {
  203. banner = banner(commentsFile);
  204. }
  205. if (banner) {
  206. outputSource = new ConcatSource("/*! " + banner + " */\n", outputSource);
  207. }
  208. }
  209. }
  210. asset.__UglifyJsPlugin = compilation.assets[file] = outputSource;
  211. if (warnings.length > 0) {
  212. compilation.warnings.push(new Error(file + " from UglifyJs\n" + warnings.join("\n")));
  213. }
  214. } catch (err) {
  215. if (err.line) {
  216. var original = sourceMap && sourceMap.originalPositionFor({
  217. line: err.line,
  218. column: err.col
  219. });
  220. if (original && original.source) {
  221. compilation.errors.push(new Error(file + " from UglifyJs\n" + err.message + " [" + requestShortener.shorten(original.source) + ":" + original.line + "," + original.column + "][" + file + ":" + err.line + "," + err.col + "]"));
  222. } else {
  223. compilation.errors.push(new Error(file + " from UglifyJs\n" + err.message + " [" + file + ":" + err.line + "," + err.col + "]"));
  224. }
  225. } else if (err.msg) {
  226. compilation.errors.push(new Error(file + " from UglifyJs\n" + err.msg));
  227. } else compilation.errors.push(new Error(file + " from UglifyJs\n" + err.stack));
  228. } finally {
  229. uglify.AST_Node.warn_function = oldWarnFunction; // eslint-disable-line camelcase
  230. }
  231. });
  232. callback();
  233. });
  234. });
  235. }
  236. }]);
  237. return UglifyJsPlugin;
  238. }();
  239. module.exports = UglifyJsPlugin;