index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _crypto = _interopRequireDefault(require("crypto"));
  7. var _path = _interopRequireDefault(require("path"));
  8. var _webpack = _interopRequireWildcard(require("webpack"));
  9. var _schemaUtils = require("schema-utils");
  10. var _serializeJavascript = _interopRequireDefault(require("serialize-javascript"));
  11. var _options = _interopRequireDefault(require("./options.json"));
  12. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  13. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  14. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  15. /*
  16. MIT License http://www.opensource.org/licenses/mit-license.php
  17. Author Tobias Koppers @sokra
  18. */
  19. const {
  20. RawSource
  21. } = // eslint-disable-next-line global-require
  22. _webpack.default.sources || require("webpack-sources");
  23. class CompressionPlugin {
  24. constructor(options = {}) {
  25. (0, _schemaUtils.validate)(_options.default, options, {
  26. name: "Compression Plugin",
  27. baseDataPath: "options"
  28. });
  29. const {
  30. test,
  31. include,
  32. exclude,
  33. cache = true,
  34. algorithm = "gzip",
  35. compressionOptions = {},
  36. filename = "[path][base].gz",
  37. threshold = 0,
  38. minRatio = 0.8,
  39. deleteOriginalAssets = false
  40. } = options;
  41. this.options = {
  42. test,
  43. include,
  44. exclude,
  45. cache,
  46. algorithm,
  47. compressionOptions,
  48. filename,
  49. threshold,
  50. minRatio,
  51. deleteOriginalAssets
  52. };
  53. this.algorithm = this.options.algorithm;
  54. if (typeof this.algorithm === "string") {
  55. // eslint-disable-next-line global-require
  56. const zlib = require("zlib");
  57. this.algorithm = zlib[this.algorithm];
  58. if (!this.algorithm) {
  59. throw new Error(`Algorithm "${this.options.algorithm}" is not found in "zlib"`);
  60. }
  61. const defaultCompressionOptions = {
  62. gzip: {
  63. level: zlib.constants.Z_BEST_COMPRESSION
  64. },
  65. deflate: {
  66. level: zlib.constants.Z_BEST_COMPRESSION
  67. },
  68. deflateRaw: {
  69. level: zlib.constants.Z_BEST_COMPRESSION
  70. },
  71. brotliCompress: {
  72. params: {
  73. [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY
  74. }
  75. }
  76. }[algorithm] || {};
  77. this.options.compressionOptions = { ...defaultCompressionOptions,
  78. ...this.options.compressionOptions
  79. };
  80. }
  81. } // eslint-disable-next-line consistent-return
  82. static getAsset(compilation, name) {
  83. // New API
  84. if (compilation.getAsset) {
  85. return compilation.getAsset(name);
  86. }
  87. if (compilation.assets[name]) {
  88. return {
  89. name,
  90. source: compilation.assets[name],
  91. info: {}
  92. };
  93. }
  94. }
  95. static emitAsset(compilation, name, source, assetInfo) {
  96. // New API
  97. if (compilation.emitAsset) {
  98. compilation.emitAsset(name, source, assetInfo);
  99. } // eslint-disable-next-line no-param-reassign
  100. compilation.assets[name] = source;
  101. }
  102. static updateAsset(compilation, name, newSource, assetInfo) {
  103. // New API
  104. if (compilation.updateAsset) {
  105. compilation.updateAsset(name, newSource, assetInfo);
  106. } // eslint-disable-next-line no-param-reassign
  107. compilation.assets[name] = newSource;
  108. }
  109. static deleteAsset(compilation, name) {
  110. // New API
  111. if (compilation.deleteAsset) {
  112. compilation.deleteAsset(name);
  113. } // eslint-disable-next-line no-param-reassign
  114. delete compilation.assets[name];
  115. }
  116. runCompressionAlgorithm(input) {
  117. return new Promise((resolve, reject) => {
  118. this.algorithm(input, this.options.compressionOptions, (error, result) => {
  119. if (error) {
  120. return reject(error);
  121. }
  122. if (!Buffer.isBuffer(result)) {
  123. // eslint-disable-next-line no-param-reassign
  124. result = Buffer.from(result);
  125. }
  126. return resolve(result);
  127. });
  128. });
  129. }
  130. async compress(compilation, assets, CacheEngine, weakCache) {
  131. const assetNames = Object.keys(typeof assets === "undefined" ? compilation.assets : assets).filter(assetName => // eslint-disable-next-line no-undefined
  132. _webpack.ModuleFilenameHelpers.matchObject.bind(undefined, this.options)(assetName));
  133. if (assetNames.length === 0) {
  134. return Promise.resolve();
  135. }
  136. const scheduledTasks = [];
  137. const cache = new CacheEngine(compilation, {
  138. cache: this.options.cache
  139. }, weakCache);
  140. for (const name of assetNames) {
  141. scheduledTasks.push((async () => {
  142. const {
  143. source: inputSource,
  144. info
  145. } = CompressionPlugin.getAsset(compilation, name);
  146. if (info.compressed) {
  147. return;
  148. }
  149. let relatedName;
  150. if (typeof this.options.algorithm === "function") {
  151. let filenameForRelatedName = this.options.filename;
  152. const index = filenameForRelatedName.lastIndexOf("?");
  153. if (index >= 0) {
  154. filenameForRelatedName = filenameForRelatedName.substr(0, index);
  155. }
  156. relatedName = `${_path.default.extname(filenameForRelatedName).slice(1)}ed`;
  157. } else if (this.options.algorithm === "gzip") {
  158. relatedName = "gzipped";
  159. } else {
  160. relatedName = `${this.options.algorithm}ed`;
  161. }
  162. if (info.related && info.related[relatedName]) {
  163. return;
  164. }
  165. let input = inputSource.source();
  166. if (!Buffer.isBuffer(input)) {
  167. input = Buffer.from(input);
  168. }
  169. if (input.length < this.options.threshold) {
  170. return;
  171. }
  172. const cacheData = {
  173. inputSource
  174. };
  175. if (CompressionPlugin.isWebpack4()) {
  176. cacheData.cacheKeys = {
  177. nodeVersion: process.version,
  178. // eslint-disable-next-line global-require
  179. "compression-webpack-plugin": require("../package.json").version,
  180. algorithm: this.algorithm,
  181. originalAlgorithm: this.options.algorithm,
  182. compressionOptions: this.options.compressionOptions,
  183. name,
  184. contentHash: _crypto.default.createHash("md4").update(input).digest("hex")
  185. };
  186. } else {
  187. cacheData.name = (0, _serializeJavascript.default)({
  188. name,
  189. algorithm: this.options.algorithm,
  190. compressionOptions: this.options.compressionOptions
  191. });
  192. }
  193. let output = await cache.get(cacheData, {
  194. RawSource
  195. });
  196. if (!output) {
  197. try {
  198. output = new RawSource(await this.runCompressionAlgorithm(input));
  199. } catch (error) {
  200. compilation.errors.push(error);
  201. return;
  202. }
  203. cacheData.output = output;
  204. await cache.store(cacheData);
  205. }
  206. if (output.source().length / input.length > this.options.minRatio) {
  207. return;
  208. }
  209. const match = /^([^?#]*)(\?[^#]*)?(#.*)?$/.exec(name);
  210. const [, replacerFile] = match;
  211. const replacerQuery = match[2] || "";
  212. const replacerFragment = match[3] || "";
  213. const replacerExt = _path.default.extname(replacerFile);
  214. const replacerBase = _path.default.basename(replacerFile);
  215. const replacerName = replacerBase.slice(0, replacerBase.length - replacerExt.length);
  216. const replacerPath = replacerFile.slice(0, replacerFile.length - replacerBase.length);
  217. const pathData = {
  218. file: replacerFile,
  219. query: replacerQuery,
  220. fragment: replacerFragment,
  221. path: replacerPath,
  222. base: replacerBase,
  223. name: replacerName,
  224. ext: replacerExt || ""
  225. };
  226. let newFilename = this.options.filename;
  227. if (typeof newFilename === "function") {
  228. newFilename = newFilename(pathData);
  229. }
  230. const newName = newFilename.replace(/\[(file|query|fragment|path|base|name|ext)]/g, (p0, p1) => pathData[p1]);
  231. const newInfo = {
  232. compressed: true
  233. };
  234. if (info.immutable && /(\[name]|\[base]|\[file])/.test(newFilename)) {
  235. newInfo.immutable = true;
  236. }
  237. if (this.options.deleteOriginalAssets) {
  238. if (this.options.deleteOriginalAssets === "keep-source-map") {
  239. // TODO `...` required only for webpack@4
  240. const updatedAssetInfo = { ...info,
  241. related: { ...info.related,
  242. sourceMap: null
  243. }
  244. };
  245. CompressionPlugin.updateAsset(compilation, name, inputSource, updatedAssetInfo);
  246. }
  247. CompressionPlugin.deleteAsset(compilation, name);
  248. } else {
  249. // TODO `...` required only for webpack@4
  250. const newOriginalInfo = { ...info,
  251. related: {
  252. [relatedName]: newName,
  253. ...info.related
  254. }
  255. };
  256. CompressionPlugin.updateAsset(compilation, name, inputSource, newOriginalInfo);
  257. }
  258. CompressionPlugin.emitAsset(compilation, newName, output, newInfo);
  259. })());
  260. }
  261. return Promise.all(scheduledTasks);
  262. }
  263. static isWebpack4() {
  264. return _webpack.version[0] === "4";
  265. }
  266. apply(compiler) {
  267. const pluginName = this.constructor.name;
  268. if (CompressionPlugin.isWebpack4()) {
  269. // eslint-disable-next-line global-require
  270. const CacheEngine = require("./Webpack4Cache").default;
  271. const weakCache = new WeakMap();
  272. compiler.hooks.emit.tapPromise({
  273. name: pluginName
  274. }, compilation => // eslint-disable-next-line no-undefined
  275. this.compress(compilation, undefined, CacheEngine, weakCache));
  276. } else {
  277. // eslint-disable-next-line global-require
  278. const CacheEngine = require("./Webpack5Cache").default;
  279. compiler.hooks.thisCompilation.tap(pluginName, compilation => {
  280. // eslint-disable-next-line global-require
  281. const Compilation = require("webpack/lib/Compilation");
  282. compilation.hooks.processAssets.tapPromise({
  283. name: pluginName,
  284. stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER
  285. }, assets => this.compress(compilation, assets, CacheEngine));
  286. compilation.hooks.statsPrinter.tap(pluginName, stats => {
  287. stats.hooks.print.for("asset.info.compressed").tap("compression-webpack-plugin", (compressed, {
  288. green,
  289. formatFlag
  290. }) => // eslint-disable-next-line no-undefined
  291. compressed ? green(formatFlag("compressed")) : undefined);
  292. });
  293. });
  294. }
  295. }
  296. }
  297. var _default = CompressionPlugin;
  298. exports.default = _default;