index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. 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; }; }(); /* eslint-disable
  6. no-param-reassign
  7. */
  8. var _crypto = require('crypto');
  9. var _crypto2 = _interopRequireDefault(_crypto);
  10. var _path = require('path');
  11. var _path2 = _interopRequireDefault(_path);
  12. var _sourceMap = require('source-map');
  13. var _webpackSources = require('webpack-sources');
  14. var _RequestShortener = require('webpack/lib/RequestShortener');
  15. var _RequestShortener2 = _interopRequireDefault(_RequestShortener);
  16. var _ModuleFilenameHelpers = require('webpack/lib/ModuleFilenameHelpers');
  17. var _ModuleFilenameHelpers2 = _interopRequireDefault(_ModuleFilenameHelpers);
  18. var _schemaUtils = require('schema-utils');
  19. var _schemaUtils2 = _interopRequireDefault(_schemaUtils);
  20. var _serializeJavascript = require('serialize-javascript');
  21. var _serializeJavascript2 = _interopRequireDefault(_serializeJavascript);
  22. var _options = require('./options.json');
  23. var _options2 = _interopRequireDefault(_options);
  24. var _uglify = require('./uglify');
  25. var _uglify2 = _interopRequireDefault(_uglify);
  26. var _versions = require('./uglify/versions');
  27. var _versions2 = _interopRequireDefault(_versions);
  28. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  29. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  30. var warningRegex = /\[.+:([0-9]+),([0-9]+)\]/;
  31. var UglifyJsPlugin = function () {
  32. function UglifyJsPlugin() {
  33. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  34. _classCallCheck(this, UglifyJsPlugin);
  35. (0, _schemaUtils2.default)(_options2.default, options, 'UglifyJs Plugin');
  36. var _options$uglifyOption = options.uglifyOptions,
  37. uglifyOptions = _options$uglifyOption === undefined ? {} : _options$uglifyOption,
  38. _options$test = options.test,
  39. test = _options$test === undefined ? /\.js(\?.*)?$/i : _options$test,
  40. _options$warningsFilt = options.warningsFilter,
  41. warningsFilter = _options$warningsFilt === undefined ? function () {
  42. return true;
  43. } : _options$warningsFilt,
  44. _options$extractComme = options.extractComments,
  45. extractComments = _options$extractComme === undefined ? false : _options$extractComme,
  46. _options$sourceMap = options.sourceMap,
  47. sourceMap = _options$sourceMap === undefined ? false : _options$sourceMap,
  48. _options$cache = options.cache,
  49. cache = _options$cache === undefined ? false : _options$cache,
  50. _options$parallel = options.parallel,
  51. parallel = _options$parallel === undefined ? false : _options$parallel,
  52. include = options.include,
  53. exclude = options.exclude;
  54. this.options = {
  55. test,
  56. warningsFilter,
  57. extractComments,
  58. sourceMap,
  59. cache,
  60. parallel,
  61. include,
  62. exclude,
  63. uglifyOptions: Object.assign({
  64. output: {
  65. comments: extractComments ? false : /^\**!|@preserve|@license|@cc_on/
  66. }
  67. }, uglifyOptions)
  68. };
  69. }
  70. _createClass(UglifyJsPlugin, [{
  71. key: 'apply',
  72. value: function apply(compiler) {
  73. var _this = this;
  74. var requestShortener = new _RequestShortener2.default(compiler.context);
  75. var buildModuleFn = function buildModuleFn(moduleArg) {
  76. // to get detailed location info about errors
  77. moduleArg.useSourceMap = true;
  78. };
  79. var optimizeFn = function optimizeFn(compilation, chunks, callback) {
  80. var uglify = new _uglify2.default({
  81. cache: _this.options.cache,
  82. parallel: _this.options.parallel
  83. });
  84. var uglifiedAssets = new WeakSet();
  85. var tasks = [];
  86. chunks.reduce(function (acc, chunk) {
  87. return acc.concat(chunk.files || []);
  88. }, []).concat(compilation.additionalChunkAssets || []).filter(_ModuleFilenameHelpers2.default.matchObject.bind(null, _this.options)).forEach(function (file) {
  89. var sourceMap = void 0;
  90. var asset = compilation.assets[file];
  91. if (uglifiedAssets.has(asset)) {
  92. return;
  93. }
  94. try {
  95. var input = void 0;
  96. var inputSourceMap = void 0;
  97. if (_this.options.sourceMap && asset.sourceAndMap) {
  98. var _asset$sourceAndMap = asset.sourceAndMap(),
  99. source = _asset$sourceAndMap.source,
  100. map = _asset$sourceAndMap.map;
  101. input = source;
  102. inputSourceMap = map;
  103. sourceMap = new _sourceMap.SourceMapConsumer(inputSourceMap);
  104. } else {
  105. input = asset.source();
  106. inputSourceMap = null;
  107. }
  108. // Handling comment extraction
  109. var commentsFile = false;
  110. if (_this.options.extractComments) {
  111. commentsFile = _this.options.extractComments.filename || `${file}.LICENSE`;
  112. if (typeof commentsFile === 'function') {
  113. commentsFile = commentsFile(file);
  114. }
  115. }
  116. var task = {
  117. file,
  118. input,
  119. sourceMap,
  120. inputSourceMap,
  121. commentsFile,
  122. extractComments: _this.options.extractComments,
  123. uglifyOptions: _this.options.uglifyOptions
  124. };
  125. if (_this.options.cache) {
  126. task.cacheKey = (0, _serializeJavascript2.default)({
  127. 'uglify-es': _versions2.default.uglify,
  128. 'uglifyjs-webpack-plugin': _versions2.default.plugin,
  129. 'uglifyjs-webpack-plugin-options': _this.options,
  130. path: compiler.outputPath ? `${compiler.outputPath}/${file}` : file,
  131. hash: _crypto2.default.createHash('md4').update(input).digest('hex')
  132. });
  133. }
  134. tasks.push(task);
  135. } catch (error) {
  136. compilation.errors.push(UglifyJsPlugin.buildError(error, file, sourceMap, requestShortener));
  137. }
  138. });
  139. uglify.runTasks(tasks, function (tasksError, results) {
  140. if (tasksError) {
  141. compilation.errors.push(tasksError);
  142. return;
  143. }
  144. results.forEach(function (data, index) {
  145. var _tasks$index = tasks[index],
  146. file = _tasks$index.file,
  147. input = _tasks$index.input,
  148. sourceMap = _tasks$index.sourceMap,
  149. inputSourceMap = _tasks$index.inputSourceMap,
  150. commentsFile = _tasks$index.commentsFile;
  151. var error = data.error,
  152. map = data.map,
  153. code = data.code,
  154. warnings = data.warnings,
  155. extractedComments = data.extractedComments;
  156. // Handling results
  157. // Error case: add errors, and go to next file
  158. if (error) {
  159. compilation.errors.push(UglifyJsPlugin.buildError(error, file, sourceMap, requestShortener));
  160. return;
  161. }
  162. var outputSource = void 0;
  163. if (map) {
  164. outputSource = new _webpackSources.SourceMapSource(code, file, JSON.parse(map), input, inputSourceMap);
  165. } else {
  166. outputSource = new _webpackSources.RawSource(code);
  167. }
  168. // Write extracted comments to commentsFile
  169. if (commentsFile && extractedComments.length > 0) {
  170. // Add a banner to the original file
  171. if (_this.options.extractComments.banner !== false) {
  172. var banner = _this.options.extractComments.banner || `For license information please see ${_path2.default.posix.basename(commentsFile)}`;
  173. if (typeof banner === 'function') {
  174. banner = banner(commentsFile);
  175. }
  176. if (banner) {
  177. outputSource = new _webpackSources.ConcatSource(`/*! ${banner} */\n`, outputSource);
  178. }
  179. }
  180. var commentsSource = new _webpackSources.RawSource(`${extractedComments.join('\n\n')}\n`);
  181. if (commentsFile in compilation.assets) {
  182. // commentsFile already exists, append new comments...
  183. if (compilation.assets[commentsFile] instanceof _webpackSources.ConcatSource) {
  184. compilation.assets[commentsFile].add('\n');
  185. compilation.assets[commentsFile].add(commentsSource);
  186. } else {
  187. compilation.assets[commentsFile] = new _webpackSources.ConcatSource(compilation.assets[commentsFile], '\n', commentsSource);
  188. }
  189. } else {
  190. compilation.assets[commentsFile] = commentsSource;
  191. }
  192. }
  193. // Updating assets
  194. uglifiedAssets.add(compilation.assets[file] = outputSource);
  195. // Handling warnings
  196. if (warnings) {
  197. var warnArr = UglifyJsPlugin.buildWarnings(warnings, file, sourceMap, _this.options.warningsFilter, requestShortener);
  198. if (warnArr.length > 0) {
  199. compilation.warnings.push(new Error(`${file} from UglifyJs\n${warnArr.join('\n')}`));
  200. }
  201. }
  202. });
  203. uglify.exit();
  204. callback();
  205. });
  206. };
  207. if (compiler.hooks) {
  208. var plugin = { name: 'UglifyJSPlugin' };
  209. compiler.hooks.compilation.tap(plugin, function (compilation) {
  210. if (_this.options.sourceMap) {
  211. compilation.hooks.buildModule.tap(plugin, buildModuleFn);
  212. }
  213. compilation.hooks.optimizeChunkAssets.tapAsync(plugin, optimizeFn.bind(_this, compilation));
  214. });
  215. } else {
  216. compiler.plugin('compilation', function (compilation) {
  217. if (_this.options.sourceMap) {
  218. compilation.plugin('build-module', buildModuleFn);
  219. }
  220. compilation.plugin('optimize-chunk-assets', optimizeFn.bind(_this, compilation));
  221. });
  222. }
  223. }
  224. }], [{
  225. key: 'buildError',
  226. value: function buildError(err, file, sourceMap, requestShortener) {
  227. // Handling error which should have line, col, filename and message
  228. if (err.line) {
  229. var original = sourceMap && sourceMap.originalPositionFor({
  230. line: err.line,
  231. column: err.col
  232. });
  233. if (original && original.source) {
  234. return new Error(`${file} from UglifyJs\n${err.message} [${requestShortener.shorten(original.source)}:${original.line},${original.column}][${file}:${err.line},${err.col}]`);
  235. }
  236. return new Error(`${file} from UglifyJs\n${err.message} [${file}:${err.line},${err.col}]`);
  237. } else if (err.stack) {
  238. return new Error(`${file} from UglifyJs\n${err.stack}`);
  239. }
  240. return new Error(`${file} from UglifyJs\n${err.message}`);
  241. }
  242. }, {
  243. key: 'buildWarnings',
  244. value: function buildWarnings(warnings, file, sourceMap, warningsFilter, requestShortener) {
  245. if (!sourceMap) {
  246. return warnings;
  247. }
  248. return warnings.reduce(function (accWarnings, warning) {
  249. var match = warningRegex.exec(warning);
  250. var line = +match[1];
  251. var column = +match[2];
  252. var original = sourceMap.originalPositionFor({
  253. line,
  254. column
  255. });
  256. if (original && original.source && original.source !== file && warningsFilter(original.source)) {
  257. accWarnings.push(`${warning.replace(warningRegex, '')}[${requestShortener.shorten(original.source)}:${original.line},${original.column}]`);
  258. }
  259. return accWarnings;
  260. }, []);
  261. }
  262. }]);
  263. return UglifyJsPlugin;
  264. }();
  265. exports.default = UglifyJsPlugin;