UglifyJsPlugin.js 9.3 KB

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