index.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. "use strict";
  2. const path = require("path");
  3. const os = require("os");
  4. const {
  5. TraceMap,
  6. originalPositionFor
  7. } = require("@jridgewell/trace-mapping");
  8. const {
  9. validate
  10. } = require("schema-utils");
  11. const serialize = require("serialize-javascript");
  12. const {
  13. Worker
  14. } = require("jest-worker");
  15. const {
  16. throttleAll,
  17. terserMinify,
  18. uglifyJsMinify,
  19. swcMinify,
  20. esbuildMinify
  21. } = require("./utils");
  22. const schema = require("./options.json");
  23. const {
  24. minify
  25. } = require("./minify");
  26. /** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
  27. /** @typedef {import("webpack").Compiler} Compiler */
  28. /** @typedef {import("webpack").Compilation} Compilation */
  29. /** @typedef {import("webpack").WebpackError} WebpackError */
  30. /** @typedef {import("webpack").Asset} Asset */
  31. /** @typedef {import("./utils.js").TerserECMA} TerserECMA */
  32. /** @typedef {import("./utils.js").TerserOptions} TerserOptions */
  33. /** @typedef {import("jest-worker").Worker} JestWorker */
  34. /** @typedef {import("@jridgewell/trace-mapping").SourceMapInput} SourceMapInput */
  35. /** @typedef {RegExp | string} Rule */
  36. /** @typedef {Rule[] | Rule} Rules */
  37. /**
  38. * @callback ExtractCommentsFunction
  39. * @param {any} astNode
  40. * @param {{ value: string, type: 'comment1' | 'comment2' | 'comment3' | 'comment4', pos: number, line: number, col: number }} comment
  41. * @returns {boolean}
  42. */
  43. /**
  44. * @typedef {boolean | 'all' | 'some' | RegExp | ExtractCommentsFunction} ExtractCommentsCondition
  45. */
  46. /**
  47. * @typedef {string | ((fileData: any) => string)} ExtractCommentsFilename
  48. */
  49. /**
  50. * @typedef {boolean | string | ((commentsFile: string) => string)} ExtractCommentsBanner
  51. */
  52. /**
  53. * @typedef {Object} ExtractCommentsObject
  54. * @property {ExtractCommentsCondition} [condition]
  55. * @property {ExtractCommentsFilename} [filename]
  56. * @property {ExtractCommentsBanner} [banner]
  57. */
  58. /**
  59. * @typedef {ExtractCommentsCondition | ExtractCommentsObject} ExtractCommentsOptions
  60. */
  61. /**
  62. * @typedef {Object} MinimizedResult
  63. * @property {string} code
  64. * @property {SourceMapInput} [map]
  65. * @property {Array<Error | string>} [errors]
  66. * @property {Array<Error | string>} [warnings]
  67. * @property {Array<string>} [extractedComments]
  68. */
  69. /**
  70. * @typedef {{ [file: string]: string }} Input
  71. */
  72. /**
  73. * @typedef {{ [key: string]: any }} CustomOptions
  74. */
  75. /**
  76. * @template T
  77. * @typedef {T extends infer U ? U : CustomOptions} InferDefaultType
  78. */
  79. /**
  80. * @typedef {Object} PredefinedOptions
  81. * @property {boolean} [module]
  82. * @property {TerserECMA} [ecma]
  83. */
  84. /**
  85. * @template T
  86. * @typedef {PredefinedOptions & InferDefaultType<T>} MinimizerOptions
  87. */
  88. /**
  89. * @template T
  90. * @callback BasicMinimizerImplementation
  91. * @param {Input} input
  92. * @param {SourceMapInput | undefined} sourceMap
  93. * @param {MinimizerOptions<T>} minifyOptions
  94. * @param {ExtractCommentsOptions | undefined} extractComments
  95. * @returns {Promise<MinimizedResult>}
  96. */
  97. /**
  98. * @typedef {object} MinimizeFunctionHelpers
  99. * @property {() => string | undefined} [getMinimizerVersion]
  100. */
  101. /**
  102. * @template T
  103. * @typedef {BasicMinimizerImplementation<T> & MinimizeFunctionHelpers} MinimizerImplementation
  104. */
  105. /**
  106. * @template T
  107. * @typedef {Object} InternalOptions
  108. * @property {string} name
  109. * @property {string} input
  110. * @property {SourceMapInput | undefined} inputSourceMap
  111. * @property {ExtractCommentsOptions | undefined} extractComments
  112. * @property {{ implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> }} minimizer
  113. */
  114. /**
  115. * @template T
  116. * @typedef {JestWorker & { transform: (options: string) => MinimizedResult, minify: (options: InternalOptions<T>) => MinimizedResult }} MinimizerWorker
  117. */
  118. /**
  119. * @typedef {undefined | boolean | number} Parallel
  120. */
  121. /**
  122. * @typedef {Object} BasePluginOptions
  123. * @property {Rules} [test]
  124. * @property {Rules} [include]
  125. * @property {Rules} [exclude]
  126. * @property {ExtractCommentsOptions} [extractComments]
  127. * @property {Parallel} [parallel]
  128. */
  129. /**
  130. * @template T
  131. * @typedef {T extends TerserOptions ? { minify?: MinimizerImplementation<T> | undefined, terserOptions?: MinimizerOptions<T> | undefined } : { minify: MinimizerImplementation<T>, terserOptions?: MinimizerOptions<T> | undefined }} DefinedDefaultMinimizerAndOptions
  132. */
  133. /**
  134. * @template T
  135. * @typedef {BasePluginOptions & { minimizer: { implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> } }} InternalPluginOptions
  136. */
  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 && 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. initializedWorker = /** @type {MinimizerWorker<T>} */
  322. new Worker(require.resolve("./minify"), {
  323. numWorkers: numberOfWorkers,
  324. enableWorkerThreads: true
  325. });
  326. // https://github.com/facebook/jest/issues/8872#issuecomment-524822081
  327. const workerStdout = initializedWorker.getStdout();
  328. if (workerStdout) {
  329. workerStdout.on("data", chunk => process.stdout.write(chunk));
  330. }
  331. const workerStderr = initializedWorker.getStderr();
  332. if (workerStderr) {
  333. workerStderr.on("data", chunk => process.stderr.write(chunk));
  334. }
  335. return initializedWorker;
  336. };
  337. }
  338. const {
  339. SourceMapSource,
  340. ConcatSource,
  341. RawSource
  342. } = compiler.webpack.sources;
  343. /** @typedef {{ extractedCommentsSource : import("webpack").sources.RawSource, commentsFilename: string }} ExtractedCommentsInfo */
  344. /** @type {Map<string, ExtractedCommentsInfo>} */
  345. const allExtractedComments = new Map();
  346. const scheduledTasks = [];
  347. for (const asset of assetsForMinify) {
  348. scheduledTasks.push(async () => {
  349. const {
  350. name,
  351. inputSource,
  352. info,
  353. cacheItem
  354. } = asset;
  355. let {
  356. output
  357. } = asset;
  358. if (!output) {
  359. let input;
  360. /** @type {SourceMapInput | undefined} */
  361. let inputSourceMap;
  362. const {
  363. source: sourceFromInputSource,
  364. map
  365. } = inputSource.sourceAndMap();
  366. input = sourceFromInputSource;
  367. if (map) {
  368. if (!TerserPlugin.isSourceMap(map)) {
  369. compilation.warnings.push( /** @type {WebpackError} */
  370. new Error(`${name} contains invalid source map`));
  371. } else {
  372. inputSourceMap = /** @type {SourceMapInput} */map;
  373. }
  374. }
  375. if (Buffer.isBuffer(input)) {
  376. input = input.toString();
  377. }
  378. /**
  379. * @type {InternalOptions<T>}
  380. */
  381. const options = {
  382. name,
  383. input,
  384. inputSourceMap,
  385. minimizer: {
  386. implementation: this.options.minimizer.implementation,
  387. // @ts-ignore https://github.com/Microsoft/TypeScript/issues/10727
  388. options: {
  389. ...this.options.minimizer.options
  390. }
  391. },
  392. extractComments: this.options.extractComments
  393. };
  394. if (typeof options.minimizer.options.module === "undefined") {
  395. if (typeof info.javascriptModule !== "undefined") {
  396. options.minimizer.options.module = info.javascriptModule;
  397. } else if (/\.mjs(\?.*)?$/i.test(name)) {
  398. options.minimizer.options.module = true;
  399. } else if (/\.cjs(\?.*)?$/i.test(name)) {
  400. options.minimizer.options.module = false;
  401. }
  402. }
  403. if (typeof options.minimizer.options.ecma === "undefined") {
  404. options.minimizer.options.ecma = TerserPlugin.getEcmaVersion(compiler.options.output.environment || {});
  405. }
  406. try {
  407. output = await (getWorker ? getWorker().transform(serialize(options)) : minify(options));
  408. } catch (error) {
  409. const hasSourceMap = inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap);
  410. compilation.errors.push( /** @type {WebpackError} */
  411. TerserPlugin.buildError(error, name, hasSourceMap ? new TraceMap( /** @type {SourceMapInput} */inputSourceMap) :
  412. // eslint-disable-next-line no-undefined
  413. undefined,
  414. // eslint-disable-next-line no-undefined
  415. hasSourceMap ? compilation.requestShortener : undefined));
  416. return;
  417. }
  418. if (typeof output.code === "undefined") {
  419. compilation.errors.push( /** @type {WebpackError} */
  420. new Error(`${name} from Terser plugin\nMinimizer doesn't return result`));
  421. return;
  422. }
  423. if (output.warnings && output.warnings.length > 0) {
  424. output.warnings = output.warnings.map(
  425. /**
  426. * @param {Error | string} item
  427. */
  428. item => TerserPlugin.buildWarning(item, name));
  429. }
  430. if (output.errors && output.errors.length > 0) {
  431. const hasSourceMap = inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap);
  432. output.errors = output.errors.map(
  433. /**
  434. * @param {Error | string} item
  435. */
  436. item => TerserPlugin.buildError(item, name, hasSourceMap ? new TraceMap( /** @type {SourceMapInput} */inputSourceMap) :
  437. // eslint-disable-next-line no-undefined
  438. undefined,
  439. // eslint-disable-next-line no-undefined
  440. hasSourceMap ? compilation.requestShortener : undefined));
  441. }
  442. let shebang;
  443. if ( /** @type {ExtractCommentsObject} */
  444. this.options.extractComments.banner !== false && output.extractedComments && output.extractedComments.length > 0 && output.code.startsWith("#!")) {
  445. const firstNewlinePosition = output.code.indexOf("\n");
  446. shebang = output.code.substring(0, firstNewlinePosition);
  447. output.code = output.code.substring(firstNewlinePosition + 1);
  448. }
  449. if (output.map) {
  450. output.source = new SourceMapSource(output.code, name, output.map, input, /** @type {SourceMapInput} */inputSourceMap, true);
  451. } else {
  452. output.source = new RawSource(output.code);
  453. }
  454. if (output.extractedComments && output.extractedComments.length > 0) {
  455. const commentsFilename = /** @type {ExtractCommentsObject} */
  456. this.options.extractComments.filename || "[file].LICENSE.txt[query]";
  457. let query = "";
  458. let filename = name;
  459. const querySplit = filename.indexOf("?");
  460. if (querySplit >= 0) {
  461. query = filename.slice(querySplit);
  462. filename = filename.slice(0, querySplit);
  463. }
  464. const lastSlashIndex = filename.lastIndexOf("/");
  465. const basename = lastSlashIndex === -1 ? filename : filename.slice(lastSlashIndex + 1);
  466. const data = {
  467. filename,
  468. basename,
  469. query
  470. };
  471. output.commentsFilename = compilation.getPath(commentsFilename, data);
  472. let banner;
  473. // Add a banner to the original file
  474. if ( /** @type {ExtractCommentsObject} */
  475. this.options.extractComments.banner !== false) {
  476. banner = /** @type {ExtractCommentsObject} */
  477. this.options.extractComments.banner || `For license information please see ${path.relative(path.dirname(name), output.commentsFilename).replace(/\\/g, "/")}`;
  478. if (typeof banner === "function") {
  479. banner = banner(output.commentsFilename);
  480. }
  481. if (banner) {
  482. output.source = new ConcatSource(shebang ? `${shebang}\n` : "", `/*! ${banner} */\n`, output.source);
  483. }
  484. }
  485. const extractedCommentsString = output.extractedComments.sort().join("\n\n");
  486. output.extractedCommentsSource = new RawSource(`${extractedCommentsString}\n`);
  487. }
  488. await cacheItem.storePromise({
  489. source: output.source,
  490. errors: output.errors,
  491. warnings: output.warnings,
  492. commentsFilename: output.commentsFilename,
  493. extractedCommentsSource: output.extractedCommentsSource
  494. });
  495. }
  496. if (output.warnings && output.warnings.length > 0) {
  497. for (const warning of output.warnings) {
  498. compilation.warnings.push( /** @type {WebpackError} */warning);
  499. }
  500. }
  501. if (output.errors && output.errors.length > 0) {
  502. for (const error of output.errors) {
  503. compilation.errors.push( /** @type {WebpackError} */error);
  504. }
  505. }
  506. /** @type {Record<string, any>} */
  507. const newInfo = {
  508. minimized: true
  509. };
  510. const {
  511. source,
  512. extractedCommentsSource
  513. } = output;
  514. // Write extracted comments to commentsFilename
  515. if (extractedCommentsSource) {
  516. const {
  517. commentsFilename
  518. } = output;
  519. newInfo.related = {
  520. license: commentsFilename
  521. };
  522. allExtractedComments.set(name, {
  523. extractedCommentsSource,
  524. commentsFilename
  525. });
  526. }
  527. compilation.updateAsset(name, source, newInfo);
  528. });
  529. }
  530. const limit = getWorker && numberOfAssets > 0 ? /** @type {number} */numberOfWorkers : scheduledTasks.length;
  531. await throttleAll(limit, scheduledTasks);
  532. if (initializedWorker) {
  533. await initializedWorker.end();
  534. }
  535. /** @typedef {{ source: import("webpack").sources.Source, commentsFilename: string, from: string }} ExtractedCommentsInfoWIthFrom */
  536. await Array.from(allExtractedComments).sort().reduce(
  537. /**
  538. * @param {Promise<unknown>} previousPromise
  539. * @param {[string, ExtractedCommentsInfo]} extractedComments
  540. * @returns {Promise<ExtractedCommentsInfoWIthFrom>}
  541. */
  542. async (previousPromise, [from, value]) => {
  543. const previous = /** @type {ExtractedCommentsInfoWIthFrom | undefined} **/
  544. await previousPromise;
  545. const {
  546. commentsFilename,
  547. extractedCommentsSource
  548. } = value;
  549. if (previous && previous.commentsFilename === commentsFilename) {
  550. const {
  551. from: previousFrom,
  552. source: prevSource
  553. } = previous;
  554. const mergedName = `${previousFrom}|${from}`;
  555. const name = `${commentsFilename}|${mergedName}`;
  556. const eTag = [prevSource, extractedCommentsSource].map(item => cache.getLazyHashedEtag(item)).reduce((previousValue, currentValue) => cache.mergeEtags(previousValue, currentValue));
  557. let source = await cache.getPromise(name, eTag);
  558. if (!source) {
  559. source = new ConcatSource(Array.from(new Set([... /** @type {string}*/prevSource.source().split("\n\n"), ... /** @type {string}*/extractedCommentsSource.source().split("\n\n")])).join("\n\n"));
  560. await cache.storePromise(name, eTag, source);
  561. }
  562. compilation.updateAsset(commentsFilename, source);
  563. return {
  564. source,
  565. commentsFilename,
  566. from: mergedName
  567. };
  568. }
  569. const existingAsset = compilation.getAsset(commentsFilename);
  570. if (existingAsset) {
  571. return {
  572. source: existingAsset.source,
  573. commentsFilename,
  574. from: commentsFilename
  575. };
  576. }
  577. compilation.emitAsset(commentsFilename, extractedCommentsSource, {
  578. extractedComments: true
  579. });
  580. return {
  581. source: extractedCommentsSource,
  582. commentsFilename,
  583. from
  584. };
  585. }, /** @type {Promise<unknown>} */Promise.resolve());
  586. }
  587. /**
  588. * @private
  589. * @param {any} environment
  590. * @returns {TerserECMA}
  591. */
  592. static getEcmaVersion(environment) {
  593. // ES 6th
  594. if (environment.arrowFunction || environment.const || environment.destructuring || environment.forOf || environment.module) {
  595. return 2015;
  596. }
  597. // ES 11th
  598. if (environment.bigIntLiteral || environment.dynamicImport) {
  599. return 2020;
  600. }
  601. return 5;
  602. }
  603. /**
  604. * @param {Compiler} compiler
  605. * @returns {void}
  606. */
  607. apply(compiler) {
  608. const pluginName = this.constructor.name;
  609. const availableNumberOfCores = TerserPlugin.getAvailableNumberOfCores(this.options.parallel);
  610. compiler.hooks.compilation.tap(pluginName, compilation => {
  611. const hooks = compiler.webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation);
  612. const data = serialize({
  613. minimizer: typeof this.options.minimizer.implementation.getMinimizerVersion !== "undefined" ? this.options.minimizer.implementation.getMinimizerVersion() || "0.0.0" : "0.0.0",
  614. options: this.options.minimizer.options
  615. });
  616. hooks.chunkHash.tap(pluginName, (chunk, hash) => {
  617. hash.update("TerserPlugin");
  618. hash.update(data);
  619. });
  620. compilation.hooks.processAssets.tapPromise({
  621. name: pluginName,
  622. stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
  623. additionalAssets: true
  624. }, assets => this.optimize(compiler, compilation, assets, {
  625. availableNumberOfCores
  626. }));
  627. compilation.hooks.statsPrinter.tap(pluginName, stats => {
  628. stats.hooks.print.for("asset.info.minimized").tap("terser-webpack-plugin", (minimized, {
  629. green,
  630. formatFlag
  631. }) => minimized ? /** @type {Function} */green( /** @type {Function} */formatFlag("minimized")) : "");
  632. });
  633. });
  634. }
  635. }
  636. TerserPlugin.terserMinify = terserMinify;
  637. TerserPlugin.uglifyJsMinify = uglifyJsMinify;
  638. TerserPlugin.swcMinify = swcMinify;
  639. TerserPlugin.esbuildMinify = esbuildMinify;
  640. module.exports = TerserPlugin;