index.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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("jest-worker").Worker} JestWorker */
  25. /** @typedef {import("@jridgewell/trace-mapping").SourceMapInput} SourceMapInput */
  26. /** @typedef {import("@jridgewell/trace-mapping").TraceMap} TraceMap */
  27. /** @typedef {RegExp | string} Rule */
  28. /** @typedef {Rule[] | Rule} Rules */
  29. /**
  30. * @callback ExtractCommentsFunction
  31. * @param {any} astNode
  32. * @param {{ value: string, type: 'comment1' | 'comment2' | 'comment3' | 'comment4', pos: number, line: number, col: number }} comment
  33. * @returns {boolean}
  34. */
  35. /**
  36. * @typedef {boolean | 'all' | 'some' | RegExp | ExtractCommentsFunction} ExtractCommentsCondition
  37. */
  38. /**
  39. * @typedef {string | ((fileData: any) => string)} ExtractCommentsFilename
  40. */
  41. /**
  42. * @typedef {boolean | string | ((commentsFile: string) => string)} ExtractCommentsBanner
  43. */
  44. /**
  45. * @typedef {Object} ExtractCommentsObject
  46. * @property {ExtractCommentsCondition} [condition]
  47. * @property {ExtractCommentsFilename} [filename]
  48. * @property {ExtractCommentsBanner} [banner]
  49. */
  50. /**
  51. * @typedef {ExtractCommentsCondition | ExtractCommentsObject} ExtractCommentsOptions
  52. */
  53. /**
  54. * @typedef {Object} MinimizedResult
  55. * @property {string} code
  56. * @property {SourceMapInput} [map]
  57. * @property {Array<Error | string>} [errors]
  58. * @property {Array<Error | string>} [warnings]
  59. * @property {Array<string>} [extractedComments]
  60. */
  61. /**
  62. * @typedef {{ [file: string]: string }} Input
  63. */
  64. /**
  65. * @typedef {{ [key: string]: any }} CustomOptions
  66. */
  67. /**
  68. * @template T
  69. * @typedef {T extends infer U ? U : CustomOptions} InferDefaultType
  70. */
  71. /**
  72. * @template T
  73. * @typedef {Object} PredefinedOptions
  74. * @property {T extends { module?: infer P } ? P : boolean | string} [module]
  75. * @property {T extends { ecma?: infer P } ? P : number | string} [ecma]
  76. */
  77. /**
  78. * @template T
  79. * @typedef {PredefinedOptions<T> & InferDefaultType<T>} MinimizerOptions
  80. */
  81. /**
  82. * @template T
  83. * @callback BasicMinimizerImplementation
  84. * @param {Input} input
  85. * @param {SourceMapInput | undefined} sourceMap
  86. * @param {MinimizerOptions<T>} minifyOptions
  87. * @param {ExtractCommentsOptions | undefined} extractComments
  88. * @returns {Promise<MinimizedResult>}
  89. */
  90. /**
  91. * @typedef {object} MinimizeFunctionHelpers
  92. * @property {() => string | undefined} [getMinimizerVersion]
  93. * @property {() => boolean | undefined} [supportsWorkerThreads]
  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 import("terser").MinifyOptions ? { 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=import("terser").MinifyOptions]
  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 = typeof os.availableParallelism === "function" ? {
  252. length: os.availableParallelism()
  253. } : os.cpus() || {
  254. length: 1
  255. };
  256. return parallel === true || typeof parallel === "undefined" ? cpus.length - 1 : Math.min(parallel || 0, cpus.length - 1);
  257. }
  258. /**
  259. * @private
  260. * @param {Compiler} compiler
  261. * @param {Compilation} compilation
  262. * @param {Record<string, import("webpack").sources.Source>} assets
  263. * @param {{availableNumberOfCores: number}} optimizeOptions
  264. * @returns {Promise<void>}
  265. */
  266. async optimize(compiler, compilation, assets, optimizeOptions) {
  267. const cache = compilation.getCache("TerserWebpackPlugin");
  268. let numberOfAssets = 0;
  269. const assetsForMinify = await Promise.all(Object.keys(assets).filter(name => {
  270. const {
  271. info
  272. } = /** @type {Asset} */compilation.getAsset(name);
  273. if (
  274. // Skip double minimize assets from child compilation
  275. info.minimized ||
  276. // Skip minimizing for extracted comments assets
  277. info.extractedComments) {
  278. return false;
  279. }
  280. if (!compiler.webpack.ModuleFilenameHelpers.matchObject.bind(
  281. // eslint-disable-next-line no-undefined
  282. undefined, this.options)(name)) {
  283. return false;
  284. }
  285. return true;
  286. }).map(async name => {
  287. const {
  288. info,
  289. source
  290. } = /** @type {Asset} */
  291. compilation.getAsset(name);
  292. const eTag = cache.getLazyHashedEtag(source);
  293. const cacheItem = cache.getItemCache(name, eTag);
  294. const output = await cacheItem.getPromise();
  295. if (!output) {
  296. numberOfAssets += 1;
  297. }
  298. return {
  299. name,
  300. info,
  301. inputSource: source,
  302. output,
  303. cacheItem
  304. };
  305. }));
  306. if (assetsForMinify.length === 0) {
  307. return;
  308. }
  309. /** @type {undefined | (() => MinimizerWorker<T>)} */
  310. let getWorker;
  311. /** @type {undefined | MinimizerWorker<T>} */
  312. let initializedWorker;
  313. /** @type {undefined | number} */
  314. let numberOfWorkers;
  315. if (optimizeOptions.availableNumberOfCores > 0) {
  316. // Do not create unnecessary workers when the number of files is less than the available cores, it saves memory
  317. numberOfWorkers = Math.min(numberOfAssets, optimizeOptions.availableNumberOfCores);
  318. // eslint-disable-next-line consistent-return
  319. getWorker = () => {
  320. if (initializedWorker) {
  321. return initializedWorker;
  322. }
  323. // eslint-disable-next-line global-require
  324. const {
  325. Worker
  326. } = require("jest-worker");
  327. initializedWorker = /** @type {MinimizerWorker<T>} */
  328. new Worker(require.resolve("./minify"), {
  329. numWorkers: numberOfWorkers,
  330. enableWorkerThreads: typeof this.options.minimizer.implementation.supportsWorkerThreads !== "undefined" ? this.options.minimizer.implementation.supportsWorkerThreads() !== false : true
  331. });
  332. // https://github.com/facebook/jest/issues/8872#issuecomment-524822081
  333. const workerStdout = initializedWorker.getStdout();
  334. if (workerStdout) {
  335. workerStdout.on("data", chunk => process.stdout.write(chunk));
  336. }
  337. const workerStderr = initializedWorker.getStderr();
  338. if (workerStderr) {
  339. workerStderr.on("data", chunk => process.stderr.write(chunk));
  340. }
  341. return initializedWorker;
  342. };
  343. }
  344. const {
  345. SourceMapSource,
  346. ConcatSource,
  347. RawSource
  348. } = compiler.webpack.sources;
  349. /** @typedef {{ extractedCommentsSource : import("webpack").sources.RawSource, commentsFilename: string }} ExtractedCommentsInfo */
  350. /** @type {Map<string, ExtractedCommentsInfo>} */
  351. const allExtractedComments = new Map();
  352. const scheduledTasks = [];
  353. for (const asset of assetsForMinify) {
  354. scheduledTasks.push(async () => {
  355. const {
  356. name,
  357. inputSource,
  358. info,
  359. cacheItem
  360. } = asset;
  361. let {
  362. output
  363. } = asset;
  364. if (!output) {
  365. let input;
  366. /** @type {SourceMapInput | undefined} */
  367. let inputSourceMap;
  368. const {
  369. source: sourceFromInputSource,
  370. map
  371. } = inputSource.sourceAndMap();
  372. input = sourceFromInputSource;
  373. if (map) {
  374. if (!TerserPlugin.isSourceMap(map)) {
  375. compilation.warnings.push( /** @type {WebpackError} */
  376. new Error(`${name} contains invalid source map`));
  377. } else {
  378. inputSourceMap = /** @type {SourceMapInput} */map;
  379. }
  380. }
  381. if (Buffer.isBuffer(input)) {
  382. input = input.toString();
  383. }
  384. /**
  385. * @type {InternalOptions<T>}
  386. */
  387. const options = {
  388. name,
  389. input,
  390. inputSourceMap,
  391. minimizer: {
  392. implementation: this.options.minimizer.implementation,
  393. // @ts-ignore https://github.com/Microsoft/TypeScript/issues/10727
  394. options: {
  395. ...this.options.minimizer.options
  396. }
  397. },
  398. extractComments: this.options.extractComments
  399. };
  400. if (typeof options.minimizer.options.module === "undefined") {
  401. if (typeof info.javascriptModule !== "undefined") {
  402. options.minimizer.options.module = /** @type {PredefinedOptions<T>["module"]} */
  403. info.javascriptModule;
  404. } else if (/\.mjs(\?.*)?$/i.test(name)) {
  405. options.minimizer.options.module = /** @type {PredefinedOptions<T>["module"]} */true;
  406. } else if (/\.cjs(\?.*)?$/i.test(name)) {
  407. options.minimizer.options.module = /** @type {PredefinedOptions<T>["module"]} */false;
  408. }
  409. }
  410. if (typeof options.minimizer.options.ecma === "undefined") {
  411. options.minimizer.options.ecma = /** @type {PredefinedOptions<T>["ecma"]} */
  412. TerserPlugin.getEcmaVersion(compiler.options.output.environment || {});
  413. }
  414. try {
  415. output = await (getWorker ? getWorker().transform(getSerializeJavascript()(options)) : minify(options));
  416. } catch (error) {
  417. const hasSourceMap = inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap);
  418. compilation.errors.push( /** @type {WebpackError} */
  419. TerserPlugin.buildError(error, name, hasSourceMap ? new (getTraceMapping().TraceMap)( /** @type {SourceMapInput} */inputSourceMap) :
  420. // eslint-disable-next-line no-undefined
  421. undefined,
  422. // eslint-disable-next-line no-undefined
  423. hasSourceMap ? compilation.requestShortener : undefined));
  424. return;
  425. }
  426. if (typeof output.code === "undefined") {
  427. compilation.errors.push( /** @type {WebpackError} */
  428. new Error(`${name} from Terser plugin\nMinimizer doesn't return result`));
  429. return;
  430. }
  431. if (output.warnings && output.warnings.length > 0) {
  432. output.warnings = output.warnings.map(
  433. /**
  434. * @param {Error | string} item
  435. */
  436. item => TerserPlugin.buildWarning(item, name));
  437. }
  438. if (output.errors && output.errors.length > 0) {
  439. const hasSourceMap = inputSourceMap && TerserPlugin.isSourceMap(inputSourceMap);
  440. output.errors = output.errors.map(
  441. /**
  442. * @param {Error | string} item
  443. */
  444. item => TerserPlugin.buildError(item, name, hasSourceMap ? new (getTraceMapping().TraceMap)( /** @type {SourceMapInput} */inputSourceMap) :
  445. // eslint-disable-next-line no-undefined
  446. undefined,
  447. // eslint-disable-next-line no-undefined
  448. hasSourceMap ? compilation.requestShortener : undefined));
  449. }
  450. let shebang;
  451. if ( /** @type {ExtractCommentsObject} */
  452. this.options.extractComments.banner !== false && output.extractedComments && output.extractedComments.length > 0 && output.code.startsWith("#!")) {
  453. const firstNewlinePosition = output.code.indexOf("\n");
  454. shebang = output.code.substring(0, firstNewlinePosition);
  455. output.code = output.code.substring(firstNewlinePosition + 1);
  456. }
  457. if (output.map) {
  458. output.source = new SourceMapSource(output.code, name, output.map, input, /** @type {SourceMapInput} */inputSourceMap, true);
  459. } else {
  460. output.source = new RawSource(output.code);
  461. }
  462. if (output.extractedComments && output.extractedComments.length > 0) {
  463. const commentsFilename = /** @type {ExtractCommentsObject} */
  464. this.options.extractComments.filename || "[file].LICENSE.txt[query]";
  465. let query = "";
  466. let filename = name;
  467. const querySplit = filename.indexOf("?");
  468. if (querySplit >= 0) {
  469. query = filename.slice(querySplit);
  470. filename = filename.slice(0, querySplit);
  471. }
  472. const lastSlashIndex = filename.lastIndexOf("/");
  473. const basename = lastSlashIndex === -1 ? filename : filename.slice(lastSlashIndex + 1);
  474. const data = {
  475. filename,
  476. basename,
  477. query
  478. };
  479. output.commentsFilename = compilation.getPath(commentsFilename, data);
  480. let banner;
  481. // Add a banner to the original file
  482. if ( /** @type {ExtractCommentsObject} */
  483. this.options.extractComments.banner !== false) {
  484. banner = /** @type {ExtractCommentsObject} */
  485. this.options.extractComments.banner || `For license information please see ${path.relative(path.dirname(name), output.commentsFilename).replace(/\\/g, "/")}`;
  486. if (typeof banner === "function") {
  487. banner = banner(output.commentsFilename);
  488. }
  489. if (banner) {
  490. output.source = new ConcatSource(shebang ? `${shebang}\n` : "", `/*! ${banner} */\n`, output.source);
  491. }
  492. }
  493. const extractedCommentsString = output.extractedComments.sort().join("\n\n");
  494. output.extractedCommentsSource = new RawSource(`${extractedCommentsString}\n`);
  495. }
  496. await cacheItem.storePromise({
  497. source: output.source,
  498. errors: output.errors,
  499. warnings: output.warnings,
  500. commentsFilename: output.commentsFilename,
  501. extractedCommentsSource: output.extractedCommentsSource
  502. });
  503. }
  504. if (output.warnings && output.warnings.length > 0) {
  505. for (const warning of output.warnings) {
  506. compilation.warnings.push( /** @type {WebpackError} */warning);
  507. }
  508. }
  509. if (output.errors && output.errors.length > 0) {
  510. for (const error of output.errors) {
  511. compilation.errors.push( /** @type {WebpackError} */error);
  512. }
  513. }
  514. /** @type {Record<string, any>} */
  515. const newInfo = {
  516. minimized: true
  517. };
  518. const {
  519. source,
  520. extractedCommentsSource
  521. } = output;
  522. // Write extracted comments to commentsFilename
  523. if (extractedCommentsSource) {
  524. const {
  525. commentsFilename
  526. } = output;
  527. newInfo.related = {
  528. license: commentsFilename
  529. };
  530. allExtractedComments.set(name, {
  531. extractedCommentsSource,
  532. commentsFilename
  533. });
  534. }
  535. compilation.updateAsset(name, source, newInfo);
  536. });
  537. }
  538. const limit = getWorker && numberOfAssets > 0 ? ( /** @type {number} */numberOfWorkers) : scheduledTasks.length;
  539. await throttleAll(limit, scheduledTasks);
  540. if (initializedWorker) {
  541. await initializedWorker.end();
  542. }
  543. /** @typedef {{ source: import("webpack").sources.Source, commentsFilename: string, from: string }} ExtractedCommentsInfoWIthFrom */
  544. await Array.from(allExtractedComments).sort().reduce(
  545. /**
  546. * @param {Promise<unknown>} previousPromise
  547. * @param {[string, ExtractedCommentsInfo]} extractedComments
  548. * @returns {Promise<ExtractedCommentsInfoWIthFrom>}
  549. */
  550. async (previousPromise, [from, value]) => {
  551. const previous = /** @type {ExtractedCommentsInfoWIthFrom | undefined} **/
  552. await previousPromise;
  553. const {
  554. commentsFilename,
  555. extractedCommentsSource
  556. } = value;
  557. if (previous && previous.commentsFilename === commentsFilename) {
  558. const {
  559. from: previousFrom,
  560. source: prevSource
  561. } = previous;
  562. const mergedName = `${previousFrom}|${from}`;
  563. const name = `${commentsFilename}|${mergedName}`;
  564. const eTag = [prevSource, extractedCommentsSource].map(item => cache.getLazyHashedEtag(item)).reduce((previousValue, currentValue) => cache.mergeEtags(previousValue, currentValue));
  565. let source = await cache.getPromise(name, eTag);
  566. if (!source) {
  567. source = new ConcatSource(Array.from(new Set([... /** @type {string}*/prevSource.source().split("\n\n"), ... /** @type {string}*/extractedCommentsSource.source().split("\n\n")])).join("\n\n"));
  568. await cache.storePromise(name, eTag, source);
  569. }
  570. compilation.updateAsset(commentsFilename, source);
  571. return {
  572. source,
  573. commentsFilename,
  574. from: mergedName
  575. };
  576. }
  577. const existingAsset = compilation.getAsset(commentsFilename);
  578. if (existingAsset) {
  579. return {
  580. source: existingAsset.source,
  581. commentsFilename,
  582. from: commentsFilename
  583. };
  584. }
  585. compilation.emitAsset(commentsFilename, extractedCommentsSource, {
  586. extractedComments: true
  587. });
  588. return {
  589. source: extractedCommentsSource,
  590. commentsFilename,
  591. from
  592. };
  593. }, /** @type {Promise<unknown>} */Promise.resolve());
  594. }
  595. /**
  596. * @private
  597. * @param {any} environment
  598. * @returns {number}
  599. */
  600. static getEcmaVersion(environment) {
  601. // ES 6th
  602. if (environment.arrowFunction || environment.const || environment.destructuring || environment.forOf || environment.module) {
  603. return 2015;
  604. }
  605. // ES 11th
  606. if (environment.bigIntLiteral || environment.dynamicImport) {
  607. return 2020;
  608. }
  609. return 5;
  610. }
  611. /**
  612. * @param {Compiler} compiler
  613. * @returns {void}
  614. */
  615. apply(compiler) {
  616. const pluginName = this.constructor.name;
  617. const availableNumberOfCores = TerserPlugin.getAvailableNumberOfCores(this.options.parallel);
  618. compiler.hooks.compilation.tap(pluginName, compilation => {
  619. const hooks = compiler.webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation);
  620. const data = getSerializeJavascript()({
  621. minimizer: typeof this.options.minimizer.implementation.getMinimizerVersion !== "undefined" ? this.options.minimizer.implementation.getMinimizerVersion() || "0.0.0" : "0.0.0",
  622. options: this.options.minimizer.options
  623. });
  624. hooks.chunkHash.tap(pluginName, (chunk, hash) => {
  625. hash.update("TerserPlugin");
  626. hash.update(data);
  627. });
  628. compilation.hooks.processAssets.tapPromise({
  629. name: pluginName,
  630. stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
  631. additionalAssets: true
  632. }, assets => this.optimize(compiler, compilation, assets, {
  633. availableNumberOfCores
  634. }));
  635. compilation.hooks.statsPrinter.tap(pluginName, stats => {
  636. stats.hooks.print.for("asset.info.minimized").tap("terser-webpack-plugin", (minimized, {
  637. green,
  638. formatFlag
  639. }) => minimized ? /** @type {Function} */green( /** @type {Function} */formatFlag("minimized")) : "");
  640. });
  641. });
  642. }
  643. }
  644. TerserPlugin.terserMinify = terserMinify;
  645. TerserPlugin.uglifyJsMinify = uglifyJsMinify;
  646. TerserPlugin.swcMinify = swcMinify;
  647. TerserPlugin.esbuildMinify = esbuildMinify;
  648. module.exports = TerserPlugin;