index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 = _interopRequireDefault(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.default)(_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. this.options.compressionOptions = { ...{
  62. level: 9
  63. },
  64. ...this.options.compressionOptions
  65. };
  66. }
  67. } // eslint-disable-next-line consistent-return
  68. static getAsset(compilation, name) {
  69. // New API
  70. if (compilation.getAsset) {
  71. return compilation.getAsset(name);
  72. }
  73. if (compilation.assets[name]) {
  74. return {
  75. name,
  76. source: compilation.assets[name],
  77. info: {}
  78. };
  79. }
  80. }
  81. static emitAsset(compilation, name, source, assetInfo) {
  82. // New API
  83. if (compilation.emitAsset) {
  84. compilation.emitAsset(name, source, assetInfo);
  85. } // eslint-disable-next-line no-param-reassign
  86. compilation.assets[name] = source;
  87. }
  88. static updateAsset(compilation, name, newSource, assetInfo) {
  89. // New API
  90. if (compilation.updateAsset) {
  91. compilation.updateAsset(name, newSource, assetInfo);
  92. } // eslint-disable-next-line no-param-reassign
  93. compilation.assets[name] = newSource;
  94. }
  95. static deleteAsset(compilation, name) {
  96. // New API
  97. if (compilation.deleteAsset) {
  98. compilation.deleteAsset(name);
  99. } // eslint-disable-next-line no-param-reassign
  100. delete compilation.assets[name];
  101. }
  102. runCompressionAlgorithm(input) {
  103. return new Promise((resolve, reject) => {
  104. this.algorithm(input, this.options.compressionOptions, (error, result) => {
  105. if (error) {
  106. return reject(error);
  107. }
  108. if (!Buffer.isBuffer(result)) {
  109. // eslint-disable-next-line no-param-reassign
  110. result = Buffer.from(result);
  111. }
  112. return resolve(result);
  113. });
  114. });
  115. }
  116. async compress(compilation, assets, CacheEngine, weakCache) {
  117. const assetNames = Object.keys(typeof assets === 'undefined' ? compilation.assets : assets).filter(assetName => // eslint-disable-next-line no-undefined
  118. _webpack.ModuleFilenameHelpers.matchObject.bind(undefined, this.options)(assetName));
  119. if (assetNames.length === 0) {
  120. return Promise.resolve();
  121. }
  122. const scheduledTasks = [];
  123. const cache = new CacheEngine(compilation, {
  124. cache: this.options.cache
  125. }, weakCache);
  126. for (const name of assetNames) {
  127. scheduledTasks.push((async () => {
  128. const {
  129. source: inputSource,
  130. info
  131. } = CompressionPlugin.getAsset(compilation, name);
  132. if (info.compressed) {
  133. return;
  134. }
  135. let relatedName;
  136. if (typeof this.options.algorithm === 'function') {
  137. let filenameForRelatedName = this.options.filename;
  138. const index = filenameForRelatedName.lastIndexOf('?');
  139. if (index >= 0) {
  140. filenameForRelatedName = filenameForRelatedName.substr(0, index);
  141. }
  142. relatedName = `${_path.default.extname(filenameForRelatedName).slice(1)}ed`;
  143. } else {
  144. relatedName = `${this.options.algorithm}ed`;
  145. }
  146. if (info.related && info.related[relatedName]) {
  147. return;
  148. }
  149. let input = inputSource.source();
  150. if (!Buffer.isBuffer(input)) {
  151. input = Buffer.from(input);
  152. }
  153. if (input.length < this.options.threshold) {
  154. return;
  155. }
  156. const cacheData = {
  157. inputSource
  158. };
  159. if (CompressionPlugin.isWebpack4()) {
  160. cacheData.cacheKeys = {
  161. nodeVersion: process.version,
  162. // eslint-disable-next-line global-require
  163. 'compression-webpack-plugin': require('../package.json').version,
  164. algorithm: this.algorithm,
  165. originalAlgorithm: this.options.algorithm,
  166. compressionOptions: this.options.compressionOptions,
  167. name,
  168. contentHash: _crypto.default.createHash('md4').update(input).digest('hex')
  169. };
  170. } else {
  171. cacheData.name = (0, _serializeJavascript.default)({
  172. name,
  173. algorithm: this.options.algorithm,
  174. compressionOptions: this.options.compressionOptions
  175. });
  176. }
  177. let output = await cache.get(cacheData, {
  178. RawSource
  179. });
  180. if (!output) {
  181. try {
  182. output = new RawSource(await this.runCompressionAlgorithm(input));
  183. } catch (error) {
  184. compilation.errors.push(error);
  185. return;
  186. }
  187. cacheData.output = output;
  188. await cache.store(cacheData);
  189. }
  190. if (output.source().length / input.length > this.options.minRatio) {
  191. return;
  192. }
  193. const match = /^([^?#]*)(\?[^#]*)?(#.*)?$/.exec(name);
  194. const [, replacerFile] = match;
  195. const replacerQuery = match[2] || '';
  196. const replacerFragment = match[3] || '';
  197. const replacerExt = _path.default.extname(replacerFile);
  198. const replacerBase = _path.default.basename(replacerFile);
  199. const replacerName = replacerBase.slice(0, replacerBase.length - replacerExt.length);
  200. const replacerPath = replacerFile.slice(0, replacerFile.length - replacerBase.length);
  201. const pathData = {
  202. file: replacerFile,
  203. query: replacerQuery,
  204. fragment: replacerFragment,
  205. path: replacerPath,
  206. base: replacerBase,
  207. name: replacerName,
  208. ext: replacerExt || ''
  209. };
  210. let newFilename = this.options.filename;
  211. if (typeof newFilename === 'function') {
  212. newFilename = newFilename(pathData);
  213. }
  214. const newName = newFilename.replace(/\[(file|query|fragment|path|base|name|ext)]/g, (p0, p1) => pathData[p1]);
  215. const newInfo = {
  216. compressed: true
  217. };
  218. if (info.immutable && /(\[name]|\[base]|\[file])/.test(newFilename)) {
  219. newInfo.immutable = true;
  220. }
  221. CompressionPlugin.emitAsset(compilation, newName, output, newInfo);
  222. if (this.options.deleteOriginalAssets) {
  223. // eslint-disable-next-line no-param-reassign
  224. CompressionPlugin.deleteAsset(compilation, name);
  225. } else {
  226. // TODO `...` required only for webpack@4
  227. const newOriginalInfo = { ...info,
  228. related: {
  229. [relatedName]: newName,
  230. ...info.related
  231. }
  232. };
  233. CompressionPlugin.updateAsset(compilation, name, inputSource, newOriginalInfo);
  234. }
  235. })());
  236. }
  237. return Promise.all(scheduledTasks);
  238. }
  239. static isWebpack4() {
  240. return _webpack.version[0] === '4';
  241. }
  242. apply(compiler) {
  243. const pluginName = this.constructor.name;
  244. if (CompressionPlugin.isWebpack4()) {
  245. // eslint-disable-next-line global-require
  246. const CacheEngine = require('./Webpack4Cache').default;
  247. const weakCache = new WeakMap();
  248. compiler.hooks.emit.tapPromise({
  249. name: pluginName
  250. }, compilation => // eslint-disable-next-line no-undefined
  251. this.compress(compilation, undefined, CacheEngine, weakCache));
  252. } else {
  253. // eslint-disable-next-line global-require
  254. const CacheEngine = require('./Webpack5Cache').default;
  255. compiler.hooks.compilation.tap(pluginName, compilation => {
  256. // eslint-disable-next-line global-require
  257. const Compilation = require('webpack/lib/Compilation');
  258. compilation.hooks.processAssets.tapPromise({
  259. name: pluginName,
  260. stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER
  261. }, assets => this.compress(compilation, assets, CacheEngine));
  262. compilation.hooks.statsPrinter.tap(pluginName, stats => {
  263. stats.hooks.print.for('asset.info.compressed').tap('compression-webpack-plugin', (compressed, {
  264. green,
  265. formatFlag
  266. }) => // eslint-disable-next-line no-undefined
  267. compressed ? green(formatFlag('compressed')) : undefined);
  268. });
  269. });
  270. }
  271. }
  272. }
  273. var _default = CompressionPlugin;
  274. exports.default = _default;