index.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. "use strict";
  2. const path = require("path");
  3. const os = require("os");
  4. const {
  5. validate
  6. } = require("schema-utils");
  7. const {
  8. throttleAll,
  9. memoize,
  10. terserMinify,
  11. uglifyJsMinify,
  12. swcMinify,
  13. esbuildMinify
  14. } = require("./utils");
  15. const schema = require("./options.json");
  16. const {
  17. minify
  18. } = require("./minify");
  19. /** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
  20. /** @typedef {import("webpack").Compiler} Compiler */
  21. /** @typedef {import("webpack").Compilation} Compilation */
  22. /** @typedef {import("webpack").WebpackError} WebpackError */
  23. /** @typedef {import("webpack").Asset} Asset */
  24. /** @typedef {import("./utils.js").TerserECMA} TerserECMA */
  25. /** @typedef {import("./utils.js").TerserOptions} TerserOptions */
  26. /** @typedef {import("jest-worker").Worker} JestWorker */
  27. /** @typedef {import("@jridgewell/trace-mapping").SourceMapInput} SourceMapInput */
  28. /** @typedef {import("@jridgewell/trace-mapping").TraceMap} TraceMap */
  29. /** @typedef {RegExp | string} Rule */
  30. /** @typedef {Rule[] | Rule} Rules */
  31. /**
  32. * @callback ExtractCommentsFunction
  33. * @param {any} astNode
  34. * @param {{ value: string, type: 'comment1' | 'comment2' | 'comment3' | 'comment4', pos: number, line: number, col: number }} comment
  35. * @returns {boolean}
  36. */
  37. /**
  38. * @typedef {boolean | 'all' | 'some' | RegExp | ExtractCommentsFunction} ExtractCommentsCondition
  39. */
  40. /**
  41. * @typedef {string | ((fileData: any) => string)} ExtractCommentsFilename
  42. */
  43. /**
  44. * @typedef {boolean | string | ((commentsFile: string) => string)} ExtractCommentsBanner
  45. */
  46. /**
  47. * @typedef {Object} ExtractCommentsObject
  48. * @property {ExtractCommentsCondition} [condition]
  49. * @property {ExtractCommentsFilename} [filename]
  50. * @property {ExtractCommentsBanner} [banner]
  51. */
  52. /**
  53. * @typedef {ExtractCommentsCondition | ExtractCommentsObject} ExtractCommentsOptions
  54. */
  55. /**
  56. * @typedef {Object} MinimizedResult
  57. * @property {string} code
  58. * @property {SourceMapInput} [map]
  59. * @property {Array<Error | string>} [errors]
  60. * @property {Array<Error | string>} [warnings]
  61. * @property {Array<string>} [extractedComments]
  62. */
  63. /**
  64. * @typedef {{ [file: string]: string }} Input
  65. */
  66. /**
  67. * @typedef {{ [key: string]: any }} CustomOptions
  68. */
  69. /**
  70. * @template T
  71. * @typedef {T extends infer U ? U : CustomOptions} InferDefaultType
  72. */
  73. /**
  74. * @typedef {Object} PredefinedOptions
  75. * @property {boolean} [module]
  76. * @property {TerserECMA} [ecma]
  77. */
  78. /**
  79. * @template T
  80. * @typedef {PredefinedOptions & InferDefaultType<T>} MinimizerOptions
  81. */
  82. /**
  83. * @template T
  84. * @callback BasicMinimizerImplementation
  85. * @param {Input} input
  86. * @param {SourceMapInput | undefined} sourceMap
  87. * @param {MinimizerOptions<T>} minifyOptions
  88. * @param {ExtractCommentsOptions | undefined} extractComments
  89. * @returns {Promise<MinimizedResult>}
  90. */
  91. /**
  92. * @typedef {object} MinimizeFunctionHelpers
  93. * @property {() => string | undefined} [getMinimizerVersion]
  94. */
  95. /**
  96. * @template T
  97. * @typedef {BasicMinimizerImplementation<T> & MinimizeFunctionHelpers} MinimizerImplementation
  98. */
  99. /**
  100. * @template T
  101. * @typedef {Object} InternalOptions
  102. * @property {string} name
  103. * @property {string} input
  104. * @property {SourceMapInput | undefined} inputSourceMap
  105. * @property {ExtractCommentsOptions | undefined} extractComments
  106. * @property {{ implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> }} minimizer
  107. */
  108. /**
  109. * @template T
  110. * @typedef {JestWorker & { transform: (options: string) => MinimizedResult, minify: (options: InternalOptions<T>) => MinimizedResult }} MinimizerWorker
  111. */
  112. /**
  113. * @typedef {undefined | boolean | number} Parallel
  114. */
  115. /**
  116. * @typedef {Object} BasePluginOptions
  117. * @property {Rules} [test]
  118. * @property {Rules} [include]
  119. * @property {Rules} [exclude]
  120. * @property {ExtractCommentsOptions} [extractComments]
  121. * @property {Parallel} [parallel]
  122. */
  123. /**
  124. * @template T
  125. * @typedef {T extends TerserOptions ? { minify?: MinimizerImplementation<T> | undefined, terserOptions?: MinimizerOptions<T> | undefined } : { minify: MinimizerImplementation<T>, terserOptions?: MinimizerOptions<T> | undefined }} DefinedDefaultMinimizerAndOptions
  126. */
  127. /**
  128. * @template T
  129. * @typedef {BasePluginOptions & { minimizer: { implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> } }} InternalPluginOptions
  130. */
  131. const getTraceMapping = memoize(() =>
  132. // eslint-disable-next-line global-require
  133. require("@jridgewell/trace-mapping"));
  134. const getSerializeJavascript = memoize(() =>
  135. // eslint-disable-next-line global-require
  136. require("serialize-javascript"));
  137. /**
  138. * @template [T=TerserOptions]
  139. */
  140. class TerserPlugin {
  141. /**
  142. * @param {BasePluginOptions & DefinedDefaultMinimizerAndOptions<T>} [options]
  143. */
  144. constructor(options) {
  145. validate( /** @type {Schema} */schema, options || {}, {
  146. name: "Terser Plugin",
  147. baseDataPath: "options"
  148. });
  149. // TODO make `minimizer` option instead `minify` and `terserOptions` in the next major release, also rename `terserMinify` to `terserMinimize`
  150. const {
  151. minify = ( /** @type {MinimizerImplementation<T>} */terserMinify),
  152. terserOptions = ( /** @type {MinimizerOptions<T>} */{}),
  153. test = /\.[cm]?js(\?.*)?$/i,
  154. extractComments = true,
  155. parallel = true,
  156. include,
  157. exclude
  158. } = options || {};
  159. /**
  160. * @private
  161. * @type {InternalPluginOptions<T>}
  162. */
  163. this.options = {
  164. test,
  165. extractComments,
  166. parallel,
  167. include,
  168. exclude,
  169. minimizer: {
  170. implementation: minify,
  171. options: terserOptions
  172. }
  173. };
  174. }
  175. /**
  176. * @private
  177. * @param {any} input
  178. * @returns {boolean}
  179. */
  180. static isSourceMap(input) {
  181. // All required options for `new TraceMap(...options)`
  182. // https://github.com/jridgewell/trace-mapping#usage
  183. return Boolean(input && input.version && input.sources && Array.isArray(input.sources) && typeof input.mappings === "string");
  184. }
  185. /**
  186. * @private
  187. * @param {unknown} warning
  188. * @param {string} file
  189. * @returns {Error}
  190. */
  191. static buildWarning(warning, file) {
  192. /**
  193. * @type {Error & { hideStack: true, file: string }}
  194. */
  195. // @ts-ignore
  196. const builtWarning = new Error(warning.toString());
  197. builtWarning.name = "Warning";
  198. builtWarning.hideStack = true;
  199. builtWarning.file = file;
  200. return builtWarning;
  201. }
  202. /**
  203. * @private
  204. * @param {any} error
  205. * @param {string} file
  206. * @param {TraceMap} [sourceMap]
  207. * @param {Compilation["requestShortener"]} [requestShortener]
  208. * @returns {Error}
  209. */
  210. static buildError(error, file, sourceMap, requestShortener) {
  211. /**
  212. * @type {Error & { file?: string }}
  213. */
  214. let builtError;
  215. if (typeof error === "string") {
  216. builtError = new Error(`${file} from Terser plugin\n${error}`);
  217. builtError.file = file;
  218. return builtError;
  219. }
  220. if (error.line) {
  221. const original = sourceMap && getTraceMapping().originalPositionFor(sourceMap, {
  222. line: error.line,
  223. column: error.col
  224. });
  225. if (original && original.source && requestShortener) {
  226. builtError = new Error(`${file} from Terser plugin\n${error.message} [${requestShortener.shorten(original.source)}:${original.line},${original.column}][${file}:${error.line},${error.col}]${error.stack ? `\n${error.stack.split("\n").slice(1).join("\n")}` : ""}`);
  227. builtError.file = file;
  228. return builtError;
  229. }
  230. builtError = new Error(`${file} from Terser plugin\n${error.message} [${file}:${error.line},${error.col}]${error.stack ? `\n${error.stack.split("\n").slice(1).join("\n")}` : ""}`);
  231. builtError.file = file;
  232. return builtError;
  233. }
  234. if (error.stack) {
  235. builtError = new Error(`${file} from Terser plugin\n${typeof error.message !== "undefined" ? error.message : ""}\n${error.stack}`);
  236. builtError.file = file;
  237. return builtError;
  238. }
  239. builtError = new Error(`${file} from Terser plugin\n${error.message}`);
  240. builtError.file = file;
  241. return builtError;
  242. }
  243. /**
  244. * @private
  245. * @param {Parallel} parallel
  246. * @returns {number}
  247. */
  248. static getAvailableNumberOfCores(parallel) {
  249. // In some cases cpus() returns undefined
  250. // https://github.com/nodejs/node/issues/19022
  251. const cpus = os.cpus() || {
  252. length: 1
  253. };
  254. return parallel === true ? cpus.length - 1 : Math.min(Number(parallel) || 0, cpus.length - 1);
  255. }
  256. /**
  257. * @private
  258. * @param {Compiler} compiler
  259. * @param {Compilation} compilation
  260. * @param {Record<string, import("webpack").sources.Source>} assets
  261. * @param {{availableNumberOfCores: number}} optimizeOptions
  262. * @returns {Promise<void>}
  263. */
  264. async optimize(compiler, compilation, assets, optimizeOptions) {
  265. const cache = compilation.getCache("TerserWebpackPlugin");
  266. let numberOfAssets = 0;
  267. const assetsForMinify = await Promise.all(Object.keys(assets).filter(name => {
  268. const {
  269. info
  270. } = /** @type {Asset} */compilation.getAsset(name);
  271. if (
  272. // Skip double minimize assets from child compilation
  273. info.minimized ||
  274. // Skip minimizing for extracted comments assets
  275. info.extractedComments) {
  276. return false;
  277. }
  278. if (!compiler.webpack.ModuleFilenameHelpers.matchObject.bind(
  279. // eslint-disable-next-line no-undefined
  280. undefined, this.options)(name)) {
  281. return false;
  282. }
  283. return true;
  284. }).map(async name => {
  285. const {
  286. info,
  287. source
  288. } = /** @type {Asset} */
  289. compilation.getAsset(name);
  290. const eTag = cache.getLazyHashedEtag(source);
  291. const cacheItem = cache.getItemCache(name, eTag);
  292. const output = await cacheItem.getPromise();
  293. if (!output) {
  294. numberOfAssets += 1;
  295. }
  296. return {
  297. name,
  298. info,
  299. inputSource: source,
  300. output,
  301. cacheItem
  302. };
  303. }));
  304. if (assetsForMinify.length === 0) {
  305. return;
  306. }
  307. /** @type {undefined | (() => MinimizerWorker<T>)} */
  308. let getWorker;
  309. /** @type {undefined | MinimizerWorker<T>} */
  310. let initializedWorker;
  311. /** @type {undefined | number} */
  312. let numberOfWorkers;
  313. if (optimizeOptions.availableNumberOfCores > 0) {
  314. // Do not create unnecessary workers when the number of files is less than the available cores, it saves memory
  315. numberOfWorkers = Math.min(numberOfAssets, optimizeOptions.availableNumberOfCores);
  316. // eslint-disable-next-line consistent-return
  317. getWorker = () => {
  318. if (initializedWorker) {
  319. return initializedWorker;
  320. }
  321. // eslint-disable-next-line global-require
  322. const {
  323. Worker
  324. } = require("jest-worker");
  325. initializedWorker = /** @type {MinimizerWorker<T>} */
  326. new Worker(require.resolve("./minify"), {
  327. numWorkers: numberOfWorkers,
  328. enableWorkerThreads: true
  329. });
  330. // https://github.com/facebook/jest/issues/8872#issuecomment-524822081
  331. const workerStdout = initializedWorker.getStdout();
  332. if (workerStdout) {
  333. workerStdout.on("data", chunk => process.stdout.write(chunk));
  334. }
  335. const workerStderr = initializedWorker.getStderr();
  336. if (workerStderr) {
  337. workerStderr.on("data", chunk => process.stderr.write(chunk));
  338. }
  339. return initializedWorker;
  340. };
  341. }
  342. const {
  343. SourceMapSource,
  344. ConcatSource,
  345. RawSource
  346. } = compiler.webpack.sources;
  347. /** @typedef {{ extractedCommentsSource : import("webpack").sources.RawSource, commentsFilename: string }} ExtractedCommentsInfo */
  348. /** @type {Map<string, ExtractedCommentsInfo>} */
  349. const allExtractedComments = new Map();
  350. const scheduledTasks = [];
  351. for (const asset of assetsForMinify) {
  352. scheduledTasks.push(async () => {
  353. const {
  354. name,
  355. inputSource,
  356. info,
  357. cacheItem
  358. } = asset;
  359. let {
  360. output
  361. } = asset;
  362. if (!output) {
  363. let input;
  364. /** @type {SourceMapInput | undefined} */
  365. let inputSourceMap;
  366. const {
  367. source: sourceFromInputSource,
  368. map
  369. } = inputSource.sourceAndMap();
  370. input = sourceFromInputSource;
  371. if (map) {
  372. if (!TerserPlugin.isSourceMap(map)) {
  373. compilation.warnings.push( /** @type {WebpackError} */
  374. new Error(`${name} contains invalid source map`));
  375. } else {
  376. inputSourceMap = /** @type {SourceMapInput} */map;
  377. }
  378. }
  379. if (Buffer.isBuffer(input)) {
  380. input = input.toString();
  381. }
  382. /**
  383. * @type {InternalOptions<T>}
  384. */
  385. const options = {
  386. name,
  387. input,
  388. inputSourceMap,
  389. minimizer: {
  390. implementation: this.options.minimizer.implementation,
  391. // @ts-ignore https://github.com/Microsoft/TypeScript/issues/10727
  392. options: {
  393. ...this.options.minimizer.options
  394. }
  395. },
  396. extractComments: this.options.extractComments
  397. };
  398. if (typeof options.minimizer.options.module === "undefined") {
  399. if (typeof info.javascriptModule !== "undefined") {
  400. options.minimizer.options.module = info.javascriptModule;
  401. } else if (/\.mjs(\?.*)?$/i.test(name)) {
  402. options.minimizer.options.module = true;
  403. } else if (/\.cjs(\?.*)?$/i.test(name)) {
  404. options.minimizer.options.module = false;
  405. }
  406. }
  407. if (typeof options.minimizer.options.ecma === "undefined") {
  408. options.minimizer.options.ecma = TerserPlugin.getEcmaVersion(compiler.options.output.environment || {});
  409. }
  410. try {
  411. output = await (getWorker ? getWorker().transform(getSerializeJavascript()(options)) : minify(options));
  412. } catch (error) {
  413. const hasSourceMap = inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap);
  414. compilation.errors.push( /** @type {WebpackError} */
  415. TerserPlugin.buildError(error, name, hasSourceMap ? new (getTraceMapping().TraceMap)( /** @type {SourceMapInput} */inputSourceMap) :
  416. // eslint-disable-next-line no-undefined
  417. undefined,
  418. // eslint-disable-next-line no-undefined
  419. hasSourceMap ? compilation.requestShortener : undefined));
  420. return;
  421. }
  422. if (typeof output.code === "undefined") {
  423. compilation.errors.push( /** @type {WebpackError} */
  424. new Error(`${name} from Terser plugin\nMinimizer doesn't return result`));
  425. return;
  426. }
  427. if (output.warnings && output.warnings.length > 0) {
  428. output.warnings = output.warnings.map(
  429. /**
  430. * @param {Error | string} item
  431. */
  432. item => TerserPlugin.buildWarning(item, name));
  433. }
  434. if (output.errors && output.errors.length > 0) {
  435. const hasSourceMap = inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap);
  436. output.errors = output.errors.map(
  437. /**
  438. * @param {Error | string} item
  439. */
  440. item => TerserPlugin.buildError(item, name, hasSourceMap ? new (getTraceMapping().TraceMap)( /** @type {SourceMapInput} */inputSourceMap) :
  441. // eslint-disable-next-line no-undefined
  442. undefined,
  443. // eslint-disable-next-line no-undefined
  444. hasSourceMap ? compilation.requestShortener : undefined));
  445. }
  446. let shebang;
  447. if ( /** @type {ExtractCommentsObject} */
  448. this.options.extractComments.banner !== false && output.extractedComments && output.extractedComments.length > 0 && output.code.startsWith("#!")) {
  449. const firstNewlinePosition = output.code.indexOf("\n");
  450. shebang = output.code.substring(0, firstNewlinePosition);
  451. output.code = output.code.substring(firstNewlinePosition + 1);
  452. }
  453. if (output.map) {
  454. output.source = new SourceMapSource(output.code, name, output.map, input, /** @type {SourceMapInput} */inputSourceMap, true);
  455. } else {
  456. output.source = new RawSource(output.code);
  457. }
  458. if (output.extractedComments && output.extractedComments.length > 0) {
  459. const commentsFilename = /** @type {ExtractCommentsObject} */
  460. this.options.extractComments.filename || "[file].LICENSE.txt[query]";
  461. let query = "";
  462. let filename = name;
  463. const querySplit = filename.indexOf("?");
  464. if (querySplit >= 0) {
  465. query = filename.slice(querySplit);
  466. filename = filename.slice(0, querySplit);
  467. }
  468. const lastSlashIndex = filename.lastIndexOf("/");
  469. const basename = lastSlashIndex === -1 ? filename : filename.slice(lastSlashIndex + 1);
  470. const data = {
  471. filename,
  472. basename,
  473. query
  474. };
  475. output.commentsFilename = compilation.getPath(commentsFilename, data);
  476. let banner;
  477. // Add a banner to the original file
  478. if ( /** @type {ExtractCommentsObject} */
  479. this.options.extractComments.banner !== false) {
  480. banner = /** @type {ExtractCommentsObject} */
  481. this.options.extractComments.banner || `For license information please see ${path.relative(path.dirname(name), output.commentsFilename).replace(/\\/g, "/")}`;
  482. if (typeof banner === "function") {
  483. banner = banner(output.commentsFilename);
  484. }
  485. if (banner) {
  486. output.source = new ConcatSource(shebang ? `${shebang}\n` : "", `/*! ${banner} */\n`, output.source);
  487. }
  488. }
  489. const extractedCommentsString = output.extractedComments.sort().join("\n\n");
  490. output.extractedCommentsSource = new RawSource(`${extractedCommentsString}\n`);
  491. }
  492. await cacheItem.storePromise({
  493. source: output.source,
  494. errors: output.errors,
  495. warnings: output.warnings,
  496. commentsFilename: output.commentsFilename,
  497. extractedCommentsSource: output.extractedCommentsSource
  498. });
  499. }
  500. if (output.warnings && output.warnings.length > 0) {
  501. for (const warning of output.warnings) {
  502. compilation.warnings.push( /** @type {WebpackError} */warning);
  503. }
  504. }
  505. if (output.errors && output.errors.length > 0) {
  506. for (const error of output.errors) {
  507. compilation.errors.push( /** @type {WebpackError} */error);
  508. }
  509. }
  510. /** @type {Record<string, any>} */
  511. const newInfo = {
  512. minimized: true
  513. };
  514. const {
  515. source,
  516. extractedCommentsSource
  517. } = output;
  518. // Write extracted comments to commentsFilename
  519. if (extractedCommentsSource) {
  520. const {
  521. commentsFilename
  522. } = output;
  523. newInfo.related = {
  524. license: commentsFilename
  525. };
  526. allExtractedComments.set(name, {
  527. extractedCommentsSource,
  528. commentsFilename
  529. });
  530. }
  531. compilation.updateAsset(name, source, newInfo);
  532. });
  533. }
  534. const limit = getWorker && numberOfAssets > 0 ? ( /** @type {number} */numberOfWorkers) : scheduledTasks.length;
  535. await throttleAll(limit, scheduledTasks);
  536. if (initializedWorker) {
  537. await initializedWorker.end();
  538. }
  539. /** @typedef {{ source: import("webpack").sources.Source, commentsFilename: string, from: string }} ExtractedCommentsInfoWIthFrom */
  540. await Array.from(allExtractedComments).sort().reduce(
  541. /**
  542. * @param {Promise<unknown>} previousPromise
  543. * @param {[string, ExtractedCommentsInfo]} extractedComments
  544. * @returns {Promise<ExtractedCommentsInfoWIthFrom>}
  545. */
  546. async (previousPromise, [from, value]) => {
  547. const previous = /** @type {ExtractedCommentsInfoWIthFrom | undefined} **/
  548. await previousPromise;
  549. const {
  550. commentsFilename,
  551. extractedCommentsSource
  552. } = value;
  553. if (previous && previous.commentsFilename === commentsFilename) {
  554. const {
  555. from: previousFrom,
  556. source: prevSource
  557. } = previous;
  558. const mergedName = `${previousFrom}|${from}`;
  559. const name = `${commentsFilename}|${mergedName}`;
  560. const eTag = [prevSource, extractedCommentsSource].map(item => cache.getLazyHashedEtag(item)).reduce((previousValue, currentValue) => cache.mergeEtags(previousValue, currentValue));
  561. let source = await cache.getPromise(name, eTag);
  562. if (!source) {
  563. source = new ConcatSource(Array.from(new Set([... /** @type {string}*/prevSource.source().split("\n\n"), ... /** @type {string}*/extractedCommentsSource.source().split("\n\n")])).join("\n\n"));
  564. await cache.storePromise(name, eTag, source);
  565. }
  566. compilation.updateAsset(commentsFilename, source);
  567. return {
  568. source,
  569. commentsFilename,
  570. from: mergedName
  571. };
  572. }
  573. const existingAsset = compilation.getAsset(commentsFilename);
  574. if (existingAsset) {
  575. return {
  576. source: existingAsset.source,
  577. commentsFilename,
  578. from: commentsFilename
  579. };
  580. }
  581. compilation.emitAsset(commentsFilename, extractedCommentsSource, {
  582. extractedComments: true
  583. });
  584. return {
  585. source: extractedCommentsSource,
  586. commentsFilename,
  587. from
  588. };
  589. }, /** @type {Promise<unknown>} */Promise.resolve());
  590. }
  591. /**
  592. * @private
  593. * @param {any} environment
  594. * @returns {TerserECMA}
  595. */
  596. static getEcmaVersion(environment) {
  597. // ES 6th
  598. if (environment.arrowFunction || environment.const || environment.destructuring || environment.forOf || environment.module) {
  599. return 2015;
  600. }
  601. // ES 11th
  602. if (environment.bigIntLiteral || environment.dynamicImport) {
  603. return 2020;
  604. }
  605. return 5;
  606. }
  607. /**
  608. * @param {Compiler} compiler
  609. * @returns {void}
  610. */
  611. apply(compiler) {
  612. const pluginName = this.constructor.name;
  613. const availableNumberOfCores = TerserPlugin.getAvailableNumberOfCores(this.options.parallel);
  614. compiler.hooks.compilation.tap(pluginName, compilation => {
  615. const hooks = compiler.webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation);
  616. const data = getSerializeJavascript()({
  617. minimizer: typeof this.options.minimizer.implementation.getMinimizerVersion !== "undefined" ? this.options.minimizer.implementation.getMinimizerVersion() || "0.0.0" : "0.0.0",
  618. options: this.options.minimizer.options
  619. });
  620. hooks.chunkHash.tap(pluginName, (chunk, hash) => {
  621. hash.update("TerserPlugin");
  622. hash.update(data);
  623. });
  624. compilation.hooks.processAssets.tapPromise({
  625. name: pluginName,
  626. stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
  627. additionalAssets: true
  628. }, assets => this.optimize(compiler, compilation, assets, {
  629. availableNumberOfCores
  630. }));
  631. compilation.hooks.statsPrinter.tap(pluginName, stats => {
  632. stats.hooks.print.for("asset.info.minimized").tap("terser-webpack-plugin", (minimized, {
  633. green,
  634. formatFlag
  635. }) => minimized ? /** @type {Function} */green( /** @type {Function} */formatFlag("minimized")) : "");
  636. });
  637. });
  638. }
  639. }
  640. TerserPlugin.terserMinify = terserMinify;
  641. TerserPlugin.uglifyJsMinify = uglifyJsMinify;
  642. TerserPlugin.swcMinify = swcMinify;
  643. TerserPlugin.esbuildMinify = esbuildMinify;
  644. module.exports = TerserPlugin;