index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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 {
  158. relatedName = `${this.options.algorithm}ed`;
  159. }
  160. if (info.related && info.related[relatedName]) {
  161. return;
  162. }
  163. let input = inputSource.source();
  164. if (!Buffer.isBuffer(input)) {
  165. input = Buffer.from(input);
  166. }
  167. if (input.length < this.options.threshold) {
  168. return;
  169. }
  170. const cacheData = {
  171. inputSource
  172. };
  173. if (CompressionPlugin.isWebpack4()) {
  174. cacheData.cacheKeys = {
  175. nodeVersion: process.version,
  176. // eslint-disable-next-line global-require
  177. 'compression-webpack-plugin': require('../package.json').version,
  178. algorithm: this.algorithm,
  179. originalAlgorithm: this.options.algorithm,
  180. compressionOptions: this.options.compressionOptions,
  181. name,
  182. contentHash: _crypto.default.createHash('md4').update(input).digest('hex')
  183. };
  184. } else {
  185. cacheData.name = (0, _serializeJavascript.default)({
  186. name,
  187. algorithm: this.options.algorithm,
  188. compressionOptions: this.options.compressionOptions
  189. });
  190. }
  191. let output = await cache.get(cacheData, {
  192. RawSource
  193. });
  194. if (!output) {
  195. try {
  196. output = new RawSource(await this.runCompressionAlgorithm(input));
  197. } catch (error) {
  198. compilation.errors.push(error);
  199. return;
  200. }
  201. cacheData.output = output;
  202. await cache.store(cacheData);
  203. }
  204. if (output.source().length / input.length > this.options.minRatio) {
  205. return;
  206. }
  207. const match = /^([^?#]*)(\?[^#]*)?(#.*)?$/.exec(name);
  208. const [, replacerFile] = match;
  209. const replacerQuery = match[2] || '';
  210. const replacerFragment = match[3] || '';
  211. const replacerExt = _path.default.extname(replacerFile);
  212. const replacerBase = _path.default.basename(replacerFile);
  213. const replacerName = replacerBase.slice(0, replacerBase.length - replacerExt.length);
  214. const replacerPath = replacerFile.slice(0, replacerFile.length - replacerBase.length);
  215. const pathData = {
  216. file: replacerFile,
  217. query: replacerQuery,
  218. fragment: replacerFragment,
  219. path: replacerPath,
  220. base: replacerBase,
  221. name: replacerName,
  222. ext: replacerExt || ''
  223. };
  224. let newFilename = this.options.filename;
  225. if (typeof newFilename === 'function') {
  226. newFilename = newFilename(pathData);
  227. }
  228. const newName = newFilename.replace(/\[(file|query|fragment|path|base|name|ext)]/g, (p0, p1) => pathData[p1]);
  229. const newInfo = {
  230. compressed: true
  231. };
  232. if (info.immutable && /(\[name]|\[base]|\[file])/.test(newFilename)) {
  233. newInfo.immutable = true;
  234. }
  235. CompressionPlugin.emitAsset(compilation, newName, output, newInfo);
  236. if (this.options.deleteOriginalAssets) {
  237. // eslint-disable-next-line no-param-reassign
  238. CompressionPlugin.deleteAsset(compilation, name);
  239. } else {
  240. // TODO `...` required only for webpack@4
  241. const newOriginalInfo = { ...info,
  242. related: {
  243. [relatedName]: newName,
  244. ...info.related
  245. }
  246. };
  247. CompressionPlugin.updateAsset(compilation, name, inputSource, newOriginalInfo);
  248. }
  249. })());
  250. }
  251. return Promise.all(scheduledTasks);
  252. }
  253. static isWebpack4() {
  254. return _webpack.version[0] === '4';
  255. }
  256. apply(compiler) {
  257. const pluginName = this.constructor.name;
  258. if (CompressionPlugin.isWebpack4()) {
  259. // eslint-disable-next-line global-require
  260. const CacheEngine = require('./Webpack4Cache').default;
  261. const weakCache = new WeakMap();
  262. compiler.hooks.emit.tapPromise({
  263. name: pluginName
  264. }, compilation => // eslint-disable-next-line no-undefined
  265. this.compress(compilation, undefined, CacheEngine, weakCache));
  266. } else {
  267. // eslint-disable-next-line global-require
  268. const CacheEngine = require('./Webpack5Cache').default;
  269. compiler.hooks.compilation.tap(pluginName, compilation => {
  270. // eslint-disable-next-line global-require
  271. const Compilation = require('webpack/lib/Compilation');
  272. compilation.hooks.processAssets.tapPromise({
  273. name: pluginName,
  274. stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER
  275. }, assets => this.compress(compilation, assets, CacheEngine));
  276. compilation.hooks.statsPrinter.tap(pluginName, stats => {
  277. stats.hooks.print.for('asset.info.compressed').tap('compression-webpack-plugin', (compressed, {
  278. green,
  279. formatFlag
  280. }) => // eslint-disable-next-line no-undefined
  281. compressed ? green(formatFlag('compressed')) : undefined);
  282. });
  283. });
  284. }
  285. }
  286. }
  287. var _default = CompressionPlugin;
  288. exports.default = _default;