UNPKG

8.97 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = void 0;
7
8var _os = _interopRequireDefault(require("os"));
9
10var _crypto = _interopRequireDefault(require("crypto"));
11
12var _webpack = _interopRequireWildcard(require("webpack"));
13
14var _schemaUtils = require("schema-utils");
15
16var _serializeJavascript = _interopRequireDefault(require("serialize-javascript"));
17
18var _package = _interopRequireDefault(require("html-minifier-terser/package.json"));
19
20var _pLimit = _interopRequireDefault(require("p-limit"));
21
22var _jestWorker = _interopRequireDefault(require("jest-worker"));
23
24var _options = _interopRequireDefault(require("./options.json"));
25
26var _minify = require("./minify");
27
28function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
29
30function _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; }
31
32function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
33
34// webpack 5 exposes the sources property to ensure the right version of webpack-sources is used
35const {
36 RawSource
37} = // eslint-disable-next-line global-require
38_webpack.default.sources || require('webpack-sources');
39
40class HtmlMinimizerPlugin {
41 constructor(options = {}) {
42 (0, _schemaUtils.validate)(_options.default, options, {
43 name: 'Html Minimizer Plugin',
44 baseDataPath: 'options'
45 });
46 const {
47 minify,
48 minimizerOptions = {},
49 test = /\.html(\?.*)?$/i,
50 cache = true,
51 cacheKeys = defaultCacheKeys => defaultCacheKeys,
52 parallel = true,
53 include,
54 exclude
55 } = options;
56 this.options = {
57 test,
58 cache,
59 cacheKeys,
60 parallel,
61 include,
62 exclude,
63 minify,
64 minimizerOptions
65 };
66 }
67
68 static buildError(error, file, context) {
69 return new Error(`${file} in "${context}" from Html Minimizer\n${error.stack}`);
70 }
71
72 static getAvailableNumberOfCores(parallel) {
73 // In some cases cpus() returns undefined
74 // https://github.com/nodejs/node/issues/19022
75 const cpus = _os.default.cpus() || {
76 length: 1
77 };
78 return parallel === true ? cpus.length - 1 : Math.min(Number(parallel) || 0, cpus.length - 1);
79 } // eslint-disable-next-line consistent-return
80
81
82 static getAsset(compilation, name) {
83 // New API
84 if (compilation.getAsset) {
85 return compilation.getAsset(name);
86 }
87
88 if (compilation.assets[name]) {
89 return {
90 name,
91 source: compilation.assets[name],
92 info: {}
93 };
94 }
95 }
96
97 static updateAsset(compilation, name, newSource, assetInfo) {
98 // New API
99 if (compilation.updateAsset) {
100 compilation.updateAsset(name, newSource, assetInfo);
101 } // eslint-disable-next-line no-param-reassign
102
103
104 compilation.assets[name] = newSource;
105 }
106
107 async optimize(compiler, compilation, assets, CacheEngine, weakCache) {
108 const matchObject = _webpack.ModuleFilenameHelpers.matchObject.bind( // eslint-disable-next-line no-undefined
109 undefined, this.options);
110
111 const assetNames = Object.keys(typeof assets === 'undefined' ? compilation.assets : assets).filter(assetName => matchObject(assetName));
112
113 if (assetNames.length === 0) {
114 return Promise.resolve();
115 }
116
117 const availableNumberOfCores = HtmlMinimizerPlugin.getAvailableNumberOfCores(this.options.parallel);
118 let concurrency = Infinity;
119 let worker;
120
121 if (availableNumberOfCores > 0) {
122 // Do not create unnecessary workers when the number of files is less than the available cores, it saves memory
123 const numWorkers = Math.min(assetNames.length, availableNumberOfCores);
124 concurrency = numWorkers;
125 worker = new _jestWorker.default(require.resolve('./minify'), {
126 numWorkers
127 }); // https://github.com/facebook/jest/issues/8872#issuecomment-524822081
128
129 const workerStdout = worker.getStdout();
130
131 if (workerStdout) {
132 workerStdout.on('data', chunk => {
133 return process.stdout.write(chunk);
134 });
135 }
136
137 const workerStderr = worker.getStderr();
138
139 if (workerStderr) {
140 workerStderr.on('data', chunk => {
141 return process.stderr.write(chunk);
142 });
143 }
144 }
145
146 const limit = (0, _pLimit.default)(concurrency);
147 const cache = new CacheEngine(compilation, {
148 cache: this.options.cache
149 }, weakCache);
150 const scheduledTasks = [];
151
152 for (const assetName of assetNames) {
153 scheduledTasks.push(limit(async () => {
154 const {
155 source: assetSource,
156 info
157 } = HtmlMinimizerPlugin.getAsset(compilation, assetName); // Skip double minimize assets from child compilation
158
159 if (info.minimized) {
160 return;
161 }
162
163 let input = assetSource.source();
164
165 if (Buffer.isBuffer(input)) {
166 input = input.toString();
167 }
168
169 const cacheData = {
170 assetName,
171 assetSource
172 };
173
174 if (HtmlMinimizerPlugin.isWebpack4()) {
175 if (this.options.cache) {
176 cacheData.input = input;
177 cacheData.cacheKeys = this.options.cacheKeys({
178 nodeVersion: process.version,
179 // eslint-disable-next-line global-require
180 'html-minimizer-webpack-plugin': require('../package.json').version,
181 htmlMinimizer: _package.default.version,
182 'html-minimizer-webpack-plugin-options': this.options,
183 assetName,
184 contentHash: _crypto.default.createHash('md4').update(input).digest('hex')
185 }, assetName);
186 }
187 }
188
189 let output = await cache.get(cacheData, {
190 RawSource
191 });
192
193 if (!output) {
194 try {
195 const minimizerOptions = {
196 assetName,
197 input,
198 minimizerOptions: this.options.minimizerOptions,
199 minify: this.options.minify
200 };
201 output = await (worker ? worker.transform((0, _serializeJavascript.default)(minimizerOptions)) : (0, _minify.minify)(minimizerOptions));
202 } catch (error) {
203 compilation.errors.push(HtmlMinimizerPlugin.buildError(error, assetName, compiler.context));
204 return;
205 }
206
207 output.source = new RawSource(output.html);
208 await cache.store({ ...output,
209 ...cacheData
210 });
211 }
212
213 HtmlMinimizerPlugin.updateAsset(compilation, assetName, output.source, { ...info,
214 minimized: true
215 });
216 }));
217 }
218
219 const result = await Promise.all(scheduledTasks);
220
221 if (worker) {
222 await worker.end();
223 }
224
225 return result;
226 }
227
228 static isWebpack4() {
229 return _webpack.version[0] === '4';
230 }
231
232 apply(compiler) {
233 const pluginName = this.constructor.name;
234 const weakCache = new WeakMap();
235 compiler.hooks.compilation.tap(pluginName, compilation => {
236 if (HtmlMinimizerPlugin.isWebpack4()) {
237 // eslint-disable-next-line global-require
238 const CacheEngine = require('./Webpack4Cache').default;
239
240 compilation.hooks.optimizeChunkAssets.tapPromise(pluginName, () => {
241 return this.optimize(compiler, compilation, // eslint-disable-next-line no-undefined
242 undefined, CacheEngine, weakCache);
243 });
244 } else {
245 // eslint-disable-next-line global-require
246 const CacheEngine = require('./Webpack5Cache').default; // eslint-disable-next-line global-require
247
248
249 const Compilation = require('webpack/lib/Compilation');
250
251 compilation.hooks.processAssets.tapPromise({
252 name: pluginName,
253 stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE
254 }, assets => this.optimize(compiler, compilation, assets, CacheEngine));
255 compilation.hooks.statsPrinter.tap(pluginName, stats => {
256 stats.hooks.print.for('asset.info.minimized').tap('html-minimizer-webpack-plugin', (minimized, {
257 green,
258 formatFlag
259 }) => // eslint-disable-next-line no-undefined
260 minimized ? green(formatFlag('minimized')) : undefined);
261 });
262 }
263 });
264 }
265
266}
267
268var _default = HtmlMinimizerPlugin;
269exports.default = _default;
\No newline at end of file