1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | 'use strict';
|
10 |
|
11 | const promisify = require('util').promisify;
|
12 |
|
13 | const vm = require('vm');
|
14 | const fs = require('fs');
|
15 | const _ = require('lodash');
|
16 | const path = require('path');
|
17 | const loaderUtils = require('loader-utils');
|
18 | const { CachedChildCompilation } = require('./lib/cached-child-compiler');
|
19 |
|
20 | const { createHtmlTagObject, htmlTagObjectToString, HtmlTagArray } = require('./lib/html-tags');
|
21 |
|
22 | const prettyError = require('./lib/errors.js');
|
23 | const chunkSorter = require('./lib/chunksorter.js');
|
24 | const getHtmlWebpackPluginHooks = require('./lib/hooks.js').getHtmlWebpackPluginHooks;
|
25 | const { assert } = require('console');
|
26 |
|
27 | const fsReadFileAsync = promisify(fs.readFile);
|
28 |
|
29 | class HtmlWebpackPlugin {
|
30 | |
31 |
|
32 |
|
33 | constructor (options) {
|
34 |
|
35 | this.userOptions = options || {};
|
36 | this.version = HtmlWebpackPlugin.version;
|
37 | }
|
38 |
|
39 | apply (compiler) {
|
40 |
|
41 | compiler.hooks.initialize.tap('HtmlWebpackPlugin', () => {
|
42 | const userOptions = this.userOptions;
|
43 |
|
44 |
|
45 |
|
46 | const defaultOptions = {
|
47 | template: 'auto',
|
48 | templateContent: false,
|
49 | templateParameters: templateParametersGenerator,
|
50 | filename: 'index.html',
|
51 | publicPath: userOptions.publicPath === undefined ? 'auto' : userOptions.publicPath,
|
52 | hash: false,
|
53 | inject: userOptions.scriptLoading === 'blocking' ? 'body' : 'head',
|
54 | scriptLoading: 'defer',
|
55 | compile: true,
|
56 | favicon: false,
|
57 | minify: 'auto',
|
58 | cache: true,
|
59 | showErrors: true,
|
60 | chunks: 'all',
|
61 | excludeChunks: [],
|
62 | chunksSortMode: 'auto',
|
63 | meta: {},
|
64 | base: false,
|
65 | title: 'Webpack App',
|
66 | xhtml: false
|
67 | };
|
68 |
|
69 |
|
70 | const options = Object.assign(defaultOptions, userOptions);
|
71 | this.options = options;
|
72 |
|
73 |
|
74 | assert(options.scriptLoading === 'defer' || options.scriptLoading === 'blocking', 'scriptLoading needs to be set to "defer" or "blocking');
|
75 | assert(options.inject === true || options.inject === false || options.inject === 'head' || options.inject === 'body', 'inject needs to be set to true, false, "head" or "body');
|
76 |
|
77 |
|
78 | if (!userOptions.template && options.templateContent === false && options.meta) {
|
79 | const defaultMeta = {
|
80 |
|
81 | viewport: 'width=device-width, initial-scale=1'
|
82 | };
|
83 | options.meta = Object.assign({}, options.meta, defaultMeta, userOptions.meta);
|
84 | }
|
85 |
|
86 |
|
87 | const userOptionFilename = userOptions.filename || defaultOptions.filename;
|
88 | const filenameFunction = typeof userOptionFilename === 'function'
|
89 | ? userOptionFilename
|
90 |
|
91 | : (entryName) => userOptionFilename.replace(/\[name\]/g, entryName);
|
92 |
|
93 |
|
94 | const entryNames = Object.keys(compiler.options.entry);
|
95 | const outputFileNames = new Set((entryNames.length ? entryNames : ['main']).map(filenameFunction));
|
96 |
|
97 |
|
98 | const entryOptions = Array.from(outputFileNames).map((filename) => ({
|
99 | ...options,
|
100 | filename
|
101 | }));
|
102 |
|
103 |
|
104 | entryOptions.forEach((instanceOptions) => {
|
105 | hookIntoCompiler(compiler, instanceOptions, this);
|
106 | });
|
107 | });
|
108 | }
|
109 |
|
110 | |
111 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 | evaluateCompilationResult (source, publicPath, templateFilename) {
|
122 | if (!source) {
|
123 | return Promise.reject(new Error('The child compilation didn\'t provide a result'));
|
124 | }
|
125 |
|
126 |
|
127 | if (source && source.indexOf('HTML_WEBPACK_PLUGIN_RESULT') >= 0) {
|
128 | source += ';\nHTML_WEBPACK_PLUGIN_RESULT';
|
129 | }
|
130 | const templateWithoutLoaders = templateFilename.replace(/^.+!/, '').replace(/\?.+$/, '');
|
131 | const vmContext = vm.createContext({ HTML_WEBPACK_PLUGIN: true, require: require, htmlWebpackPluginPublicPath: publicPath, ...global });
|
132 | const vmScript = new vm.Script(source, { filename: templateWithoutLoaders });
|
133 |
|
134 | let newSource;
|
135 | try {
|
136 | newSource = vmScript.runInContext(vmContext);
|
137 | } catch (e) {
|
138 | return Promise.reject(e);
|
139 | }
|
140 | if (typeof newSource === 'object' && newSource.__esModule && newSource.default) {
|
141 | newSource = newSource.default;
|
142 | }
|
143 | return typeof newSource === 'string' || typeof newSource === 'function'
|
144 | ? Promise.resolve(newSource)
|
145 | : Promise.reject(new Error('The loader "' + templateWithoutLoaders + '" didn\'t return html.'));
|
146 | }
|
147 | }
|
148 |
|
149 |
|
150 |
|
151 |
|
152 |
|
153 |
|
154 |
|
155 | function hookIntoCompiler (compiler, options, plugin) {
|
156 | const webpack = compiler.webpack;
|
157 |
|
158 |
|
159 | let assetJson;
|
160 | |
161 |
|
162 |
|
163 |
|
164 |
|
165 | let previousEmittedAssets = [];
|
166 |
|
167 | options.template = getFullTemplatePath(options.template, compiler.context);
|
168 |
|
169 |
|
170 | const childCompilerPlugin = new CachedChildCompilation(compiler);
|
171 | if (!options.templateContent) {
|
172 | childCompilerPlugin.addEntry(options.template);
|
173 | }
|
174 |
|
175 |
|
176 |
|
177 | const filename = options.filename;
|
178 | if (path.resolve(filename) === path.normalize(filename)) {
|
179 | const outputPath = (compiler.options.output.path);
|
180 | options.filename = path.relative(outputPath, filename);
|
181 | }
|
182 |
|
183 |
|
184 |
|
185 |
|
186 | options.filename = options.filename.replace(/\[(?:(\w+):)?contenthash(?::([a-z]+\d*))?(?::(\d+))?\]/ig, (match) => {
|
187 | return match.replace('contenthash', 'templatehash');
|
188 | });
|
189 |
|
190 |
|
191 |
|
192 | const isProductionLikeMode = compiler.options.mode === 'production' || !compiler.options.mode;
|
193 |
|
194 | const minify = options.minify;
|
195 | if (minify === true || (minify === 'auto' && isProductionLikeMode)) {
|
196 |
|
197 | options.minify = {
|
198 |
|
199 | collapseWhitespace: true,
|
200 | keepClosingSlash: true,
|
201 | removeComments: true,
|
202 | removeRedundantAttributes: true,
|
203 | removeScriptTypeAttributes: true,
|
204 | removeStyleLinkTypeAttributes: true,
|
205 | useShortDoctype: true
|
206 | };
|
207 | }
|
208 |
|
209 | compiler.hooks.thisCompilation.tap('HtmlWebpackPlugin',
|
210 | |
211 |
|
212 |
|
213 |
|
214 | (compilation) => {
|
215 | compilation.hooks.processAssets.tapAsync(
|
216 | {
|
217 | name: 'HtmlWebpackPlugin',
|
218 | stage:
|
219 | |
220 |
|
221 |
|
222 | webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
|
223 | },
|
224 | |
225 |
|
226 |
|
227 |
|
228 |
|
229 | (compilationAssets, callback) => {
|
230 |
|
231 | const entryNames = Array.from(compilation.entrypoints.keys());
|
232 | const filteredEntryNames = filterChunks(entryNames, options.chunks, options.excludeChunks);
|
233 | const sortedEntryNames = sortEntryChunks(filteredEntryNames, options.chunksSortMode, compilation);
|
234 |
|
235 | const templateResult = options.templateContent
|
236 | ? { mainCompilationHash: compilation.hash }
|
237 | : childCompilerPlugin.getCompilationEntryResult(options.template);
|
238 |
|
239 | if ('error' in templateResult) {
|
240 | compilation.errors.push(prettyError(templateResult.error, compiler.context).toString());
|
241 | }
|
242 |
|
243 | const compiledEntries = 'compiledEntry' in templateResult ? {
|
244 | hash: templateResult.compiledEntry.hash,
|
245 | chunk: templateResult.compiledEntry.entry
|
246 | } : {
|
247 | hash: templateResult.mainCompilationHash
|
248 | };
|
249 |
|
250 | const childCompilationOutputName = compilation.getAssetPath(options.filename, compiledEntries);
|
251 |
|
252 |
|
253 |
|
254 | const isCompilationCached = templateResult.mainCompilationHash !== compilation.hash;
|
255 |
|
256 |
|
257 | const htmlPublicPath = getPublicPath(compilation, childCompilationOutputName, options.publicPath);
|
258 |
|
259 |
|
260 | const assets = htmlWebpackPluginAssets(compilation, sortedEntryNames, htmlPublicPath);
|
261 |
|
262 |
|
263 | const newAssetJson = JSON.stringify(getAssetFiles(assets));
|
264 | if (isCompilationCached && options.cache && assetJson === newAssetJson) {
|
265 | previousEmittedAssets.forEach(({ name, html }) => {
|
266 | compilation.emitAsset(name, new webpack.sources.RawSource(html, false));
|
267 | });
|
268 | return callback();
|
269 | } else {
|
270 | previousEmittedAssets = [];
|
271 | assetJson = newAssetJson;
|
272 | }
|
273 |
|
274 |
|
275 |
|
276 |
|
277 | const assetsPromise = getFaviconPublicPath(options.favicon, compilation, assets.publicPath)
|
278 | .then((faviconPath) => {
|
279 | assets.favicon = faviconPath;
|
280 | return getHtmlWebpackPluginHooks(compilation).beforeAssetTagGeneration.promise({
|
281 | assets: assets,
|
282 | outputName: childCompilationOutputName,
|
283 | plugin: plugin
|
284 | });
|
285 | });
|
286 |
|
287 |
|
288 | const assetTagGroupsPromise = assetsPromise
|
289 |
|
290 | .then(({ assets }) => getHtmlWebpackPluginHooks(compilation).alterAssetTags.promise({
|
291 | assetTags: {
|
292 | scripts: generatedScriptTags(assets.js),
|
293 | styles: generateStyleTags(assets.css),
|
294 | meta: [
|
295 | ...generateBaseTag(options.base),
|
296 | ...generatedMetaTags(options.meta),
|
297 | ...generateFaviconTags(assets.favicon)
|
298 | ]
|
299 | },
|
300 | outputName: childCompilationOutputName,
|
301 | publicPath: htmlPublicPath,
|
302 | plugin: plugin
|
303 | }))
|
304 | .then(({ assetTags }) => {
|
305 |
|
306 | const scriptTarget = options.inject === 'head' ||
|
307 | (options.inject !== 'body' && options.scriptLoading !== 'blocking') ? 'head' : 'body';
|
308 |
|
309 | const assetGroups = generateAssetGroups(assetTags, scriptTarget);
|
310 |
|
311 | return getHtmlWebpackPluginHooks(compilation).alterAssetTagGroups.promise({
|
312 | headTags: assetGroups.headTags,
|
313 | bodyTags: assetGroups.bodyTags,
|
314 | outputName: childCompilationOutputName,
|
315 | publicPath: htmlPublicPath,
|
316 | plugin: plugin
|
317 | });
|
318 | });
|
319 |
|
320 |
|
321 | const templateEvaluationPromise = Promise.resolve()
|
322 | .then(() => {
|
323 | if ('error' in templateResult) {
|
324 | return options.showErrors ? prettyError(templateResult.error, compiler.context).toHtml() : 'ERROR';
|
325 | }
|
326 |
|
327 | if (options.templateContent !== false) {
|
328 | return options.templateContent;
|
329 | }
|
330 |
|
331 |
|
332 | return ('compiledEntry' in templateResult)
|
333 | ? plugin.evaluateCompilationResult(templateResult.compiledEntry.content, htmlPublicPath, options.template)
|
334 | : Promise.reject(new Error('Child compilation contained no compiledEntry'));
|
335 | });
|
336 | const templateExectutionPromise = Promise.all([assetsPromise, assetTagGroupsPromise, templateEvaluationPromise])
|
337 |
|
338 | .then(([assetsHookResult, assetTags, compilationResult]) => typeof compilationResult !== 'function'
|
339 | ? compilationResult
|
340 | : executeTemplate(compilationResult, assetsHookResult.assets, { headTags: assetTags.headTags, bodyTags: assetTags.bodyTags }, compilation));
|
341 |
|
342 | const injectedHtmlPromise = Promise.all([assetTagGroupsPromise, templateExectutionPromise])
|
343 |
|
344 | .then(([assetTags, html]) => {
|
345 | const pluginArgs = { html, headTags: assetTags.headTags, bodyTags: assetTags.bodyTags, plugin: plugin, outputName: childCompilationOutputName };
|
346 | return getHtmlWebpackPluginHooks(compilation).afterTemplateExecution.promise(pluginArgs);
|
347 | })
|
348 | .then(({ html, headTags, bodyTags }) => {
|
349 | return postProcessHtml(html, assets, { headTags, bodyTags });
|
350 | });
|
351 |
|
352 | const emitHtmlPromise = injectedHtmlPromise
|
353 |
|
354 | .then((html) => {
|
355 | const pluginArgs = { html, plugin: plugin, outputName: childCompilationOutputName };
|
356 | return getHtmlWebpackPluginHooks(compilation).beforeEmit.promise(pluginArgs)
|
357 | .then(result => result.html);
|
358 | })
|
359 | .catch(err => {
|
360 |
|
361 |
|
362 | compilation.errors.push(prettyError(err, compiler.context).toString());
|
363 | return options.showErrors ? prettyError(err, compiler.context).toHtml() : 'ERROR';
|
364 | })
|
365 | .then(html => {
|
366 |
|
367 |
|
368 |
|
369 | const finalOutputName = childCompilationOutputName.replace(/\[(?:(\w+):)?templatehash(?::([a-z]+\d*))?(?::(\d+))?\]/ig, (_, hashType, digestType, maxLength) => {
|
370 | return loaderUtils.getHashDigest(Buffer.from(html, 'utf8'), hashType, digestType, parseInt(maxLength, 10));
|
371 | });
|
372 |
|
373 | compilation.emitAsset(finalOutputName, new webpack.sources.RawSource(html, false));
|
374 | previousEmittedAssets.push({ name: finalOutputName, html });
|
375 | return finalOutputName;
|
376 | })
|
377 | .then((finalOutputName) => getHtmlWebpackPluginHooks(compilation).afterEmit.promise({
|
378 | outputName: finalOutputName,
|
379 | plugin: plugin
|
380 | }).catch(err => {
|
381 | console.error(err);
|
382 | return null;
|
383 | }).then(() => null));
|
384 |
|
385 |
|
386 |
|
387 | emitHtmlPromise.then(() => {
|
388 | callback();
|
389 | });
|
390 | });
|
391 | });
|
392 |
|
393 | |
394 |
|
395 |
|
396 |
|
397 |
|
398 |
|
399 |
|
400 |
|
401 |
|
402 |
|
403 |
|
404 |
|
405 |
|
406 |
|
407 |
|
408 |
|
409 | function getTemplateParameters (compilation, assets, assetTags) {
|
410 | const templateParameters = options.templateParameters;
|
411 | if (templateParameters === false) {
|
412 | return Promise.resolve({});
|
413 | }
|
414 | if (typeof templateParameters !== 'function' && typeof templateParameters !== 'object') {
|
415 | throw new Error('templateParameters has to be either a function or an object');
|
416 | }
|
417 | const templateParameterFunction = typeof templateParameters === 'function'
|
418 |
|
419 | ? templateParameters
|
420 |
|
421 | : (compilation, assets, assetTags, options) => Object.assign({},
|
422 | templateParametersGenerator(compilation, assets, assetTags, options),
|
423 | templateParameters
|
424 | );
|
425 | const preparedAssetTags = {
|
426 | headTags: prepareAssetTagGroupForRendering(assetTags.headTags),
|
427 | bodyTags: prepareAssetTagGroupForRendering(assetTags.bodyTags)
|
428 | };
|
429 | return Promise
|
430 | .resolve()
|
431 | .then(() => templateParameterFunction(compilation, assets, preparedAssetTags, options));
|
432 | }
|
433 |
|
434 | |
435 |
|
436 |
|
437 |
|
438 |
|
439 |
|
440 |
|
441 |
|
442 |
|
443 |
|
444 |
|
445 |
|
446 |
|
447 |
|
448 |
|
449 |
|
450 |
|
451 |
|
452 |
|
453 | function executeTemplate (templateFunction, assets, assetTags, compilation) {
|
454 |
|
455 | const templateParamsPromise = getTemplateParameters(compilation, assets, assetTags);
|
456 | return templateParamsPromise.then((templateParams) => {
|
457 | try {
|
458 |
|
459 |
|
460 | return templateFunction(templateParams);
|
461 | } catch (e) {
|
462 | compilation.errors.push(new Error('Template execution failed: ' + e));
|
463 | return Promise.reject(e);
|
464 | }
|
465 | });
|
466 | }
|
467 |
|
468 | |
469 |
|
470 |
|
471 |
|
472 |
|
473 |
|
474 |
|
475 |
|
476 |
|
477 |
|
478 |
|
479 |
|
480 |
|
481 |
|
482 | function postProcessHtml (html, assets, assetTags) {
|
483 | if (typeof html !== 'string') {
|
484 | return Promise.reject(new Error('Expected html to be a string but got ' + JSON.stringify(html)));
|
485 | }
|
486 | const htmlAfterInjection = options.inject
|
487 | ? injectAssetsIntoHtml(html, assets, assetTags)
|
488 | : html;
|
489 | const htmlAfterMinification = minifyHtml(htmlAfterInjection);
|
490 | return Promise.resolve(htmlAfterMinification);
|
491 | }
|
492 |
|
493 | |
494 |
|
495 |
|
496 |
|
497 |
|
498 |
|
499 |
|
500 | function addFileToAssets (filename, compilation) {
|
501 | filename = path.resolve(compilation.compiler.context, filename);
|
502 | return fsReadFileAsync(filename)
|
503 | .then(source => new webpack.sources.RawSource(source, false))
|
504 | .catch(() => Promise.reject(new Error('HtmlWebpackPlugin: could not load file ' + filename)))
|
505 | .then(rawSource => {
|
506 | const basename = path.basename(filename);
|
507 | compilation.fileDependencies.add(filename);
|
508 | compilation.emitAsset(basename, rawSource);
|
509 | return basename;
|
510 | });
|
511 | }
|
512 |
|
513 | |
514 |
|
515 |
|
516 |
|
517 |
|
518 |
|
519 | function sortEntryChunks (entryNames, sortMode, compilation) {
|
520 |
|
521 | if (typeof sortMode === 'function') {
|
522 | return entryNames.sort(sortMode);
|
523 | }
|
524 |
|
525 | if (typeof chunkSorter[sortMode] !== 'undefined') {
|
526 | return chunkSorter[sortMode](entryNames, compilation, options);
|
527 | }
|
528 | throw new Error('"' + sortMode + '" is not a valid chunk sort mode');
|
529 | }
|
530 |
|
531 | |
532 |
|
533 |
|
534 |
|
535 |
|
536 |
|
537 | function filterChunks (chunks, includedChunks, excludedChunks) {
|
538 | return chunks.filter(chunkName => {
|
539 |
|
540 | if (Array.isArray(includedChunks) && includedChunks.indexOf(chunkName) === -1) {
|
541 | return false;
|
542 | }
|
543 |
|
544 | if (Array.isArray(excludedChunks) && excludedChunks.indexOf(chunkName) !== -1) {
|
545 | return false;
|
546 | }
|
547 |
|
548 | return true;
|
549 | });
|
550 | }
|
551 |
|
552 | |
553 |
|
554 |
|
555 |
|
556 |
|
557 |
|
558 |
|
559 |
|
560 |
|
561 | function getPublicPath (compilation, childCompilationOutputName, customPublicPath) {
|
562 | const compilationHash = compilation.hash;
|
563 |
|
564 | |
565 |
|
566 |
|
567 |
|
568 |
|
569 | const webpackPublicPath = compilation.getAssetPath(compilation.outputOptions.publicPath, { hash: compilationHash });
|
570 |
|
571 |
|
572 | const isPublicPathDefined = webpackPublicPath !== 'auto';
|
573 |
|
574 | let publicPath =
|
575 |
|
576 | customPublicPath !== 'auto'
|
577 | ? customPublicPath
|
578 | : (isPublicPathDefined
|
579 |
|
580 | ? webpackPublicPath
|
581 |
|
582 | : path.relative(path.resolve(compilation.options.output.path, path.dirname(childCompilationOutputName)), compilation.options.output.path)
|
583 | .split(path.sep).join('/')
|
584 | );
|
585 |
|
586 | if (publicPath.length && publicPath.substr(-1, 1) !== '/') {
|
587 | publicPath += '/';
|
588 | }
|
589 |
|
590 | return publicPath;
|
591 | }
|
592 |
|
593 | |
594 |
|
595 |
|
596 |
|
597 |
|
598 |
|
599 |
|
600 |
|
601 |
|
602 |
|
603 |
|
604 |
|
605 |
|
606 |
|
607 | function htmlWebpackPluginAssets (compilation, entryNames, publicPath) {
|
608 | const compilationHash = compilation.hash;
|
609 | |
610 |
|
611 |
|
612 |
|
613 |
|
614 |
|
615 |
|
616 |
|
617 |
|
618 | const assets = {
|
619 |
|
620 | publicPath,
|
621 |
|
622 | js: [],
|
623 |
|
624 | css: [],
|
625 |
|
626 | manifest: Object.keys(compilation.assets).find(assetFile => path.extname(assetFile) === '.appcache'),
|
627 |
|
628 | favicon: undefined
|
629 | };
|
630 |
|
631 |
|
632 | if (options.hash && assets.manifest) {
|
633 | assets.manifest = appendHash(assets.manifest, compilationHash);
|
634 | }
|
635 |
|
636 |
|
637 | const entryPointPublicPathMap = {};
|
638 | const extensionRegexp = /\.(css|js|mjs)(\?|$)/;
|
639 | for (let i = 0; i < entryNames.length; i++) {
|
640 | const entryName = entryNames[i];
|
641 |
|
642 | const entryPointUnfilteredFiles = compilation.entrypoints.get(entryName).getFiles();
|
643 |
|
644 | const entryPointFiles = entryPointUnfilteredFiles.filter((chunkFile) => {
|
645 |
|
646 |
|
647 |
|
648 | const asset = compilation.getAsset && compilation.getAsset(chunkFile);
|
649 | if (!asset) {
|
650 | return true;
|
651 | }
|
652 |
|
653 | const assetMetaInformation = asset.info || {};
|
654 | return !(assetMetaInformation.hotModuleReplacement || assetMetaInformation.development);
|
655 | });
|
656 |
|
657 |
|
658 |
|
659 |
|
660 | const entryPointPublicPaths = entryPointFiles
|
661 | .map(chunkFile => {
|
662 | const entryPointPublicPath = publicPath + urlencodePath(chunkFile);
|
663 | return options.hash
|
664 | ? appendHash(entryPointPublicPath, compilationHash)
|
665 | : entryPointPublicPath;
|
666 | });
|
667 |
|
668 | entryPointPublicPaths.forEach((entryPointPublicPath) => {
|
669 | const extMatch = extensionRegexp.exec(entryPointPublicPath);
|
670 |
|
671 | if (!extMatch) {
|
672 | return;
|
673 | }
|
674 |
|
675 |
|
676 | if (entryPointPublicPathMap[entryPointPublicPath]) {
|
677 | return;
|
678 | }
|
679 | entryPointPublicPathMap[entryPointPublicPath] = true;
|
680 |
|
681 | const ext = extMatch[1] === 'mjs' ? 'js' : extMatch[1];
|
682 | assets[ext].push(entryPointPublicPath);
|
683 | });
|
684 | }
|
685 | return assets;
|
686 | }
|
687 |
|
688 | |
689 |
|
690 |
|
691 |
|
692 |
|
693 |
|
694 |
|
695 |
|
696 |
|
697 | function getFaviconPublicPath (faviconFilePath, compilation, publicPath) {
|
698 | if (!faviconFilePath) {
|
699 | return Promise.resolve(undefined);
|
700 | }
|
701 | return addFileToAssets(faviconFilePath, compilation)
|
702 | .then((faviconName) => {
|
703 | const faviconPath = publicPath + faviconName;
|
704 | if (options.hash) {
|
705 | return appendHash(faviconPath, compilation.hash);
|
706 | }
|
707 | return faviconPath;
|
708 | });
|
709 | }
|
710 |
|
711 | |
712 |
|
713 |
|
714 |
|
715 |
|
716 | function generatedScriptTags (jsAssets) {
|
717 | return jsAssets.map(scriptAsset => ({
|
718 | tagName: 'script',
|
719 | voidTag: false,
|
720 | meta: { plugin: 'html-webpack-plugin' },
|
721 | attributes: {
|
722 | defer: options.scriptLoading !== 'blocking',
|
723 | src: scriptAsset
|
724 | }
|
725 | }));
|
726 | }
|
727 |
|
728 | |
729 |
|
730 |
|
731 |
|
732 |
|
733 | function generateStyleTags (cssAssets) {
|
734 | return cssAssets.map(styleAsset => ({
|
735 | tagName: 'link',
|
736 | voidTag: true,
|
737 | meta: { plugin: 'html-webpack-plugin' },
|
738 | attributes: {
|
739 | href: styleAsset,
|
740 | rel: 'stylesheet'
|
741 | }
|
742 | }));
|
743 | }
|
744 |
|
745 | |
746 |
|
747 |
|
748 |
|
749 |
|
750 |
|
751 |
|
752 |
|
753 | function generateBaseTag (baseOption) {
|
754 | if (baseOption === false) {
|
755 | return [];
|
756 | } else {
|
757 | return [{
|
758 | tagName: 'base',
|
759 | voidTag: true,
|
760 | meta: { plugin: 'html-webpack-plugin' },
|
761 | attributes: (typeof baseOption === 'string') ? {
|
762 | href: baseOption
|
763 | } : baseOption
|
764 | }];
|
765 | }
|
766 | }
|
767 |
|
768 | |
769 |
|
770 |
|
771 |
|
772 |
|
773 |
|
774 |
|
775 |
|
776 |
|
777 |
|
778 | function generatedMetaTags (metaOptions) {
|
779 | if (metaOptions === false) {
|
780 | return [];
|
781 | }
|
782 |
|
783 |
|
784 |
|
785 | const metaTagAttributeObjects = Object.keys(metaOptions)
|
786 | .map((metaName) => {
|
787 | const metaTagContent = metaOptions[metaName];
|
788 | return (typeof metaTagContent === 'string') ? {
|
789 | name: metaName,
|
790 | content: metaTagContent
|
791 | } : metaTagContent;
|
792 | })
|
793 | .filter((attribute) => attribute !== false);
|
794 |
|
795 |
|
796 | return metaTagAttributeObjects.map((metaTagAttributes) => {
|
797 | if (metaTagAttributes === false) {
|
798 | throw new Error('Invalid meta tag');
|
799 | }
|
800 | return {
|
801 | tagName: 'meta',
|
802 | voidTag: true,
|
803 | meta: { plugin: 'html-webpack-plugin' },
|
804 | attributes: metaTagAttributes
|
805 | };
|
806 | });
|
807 | }
|
808 |
|
809 | |
810 |
|
811 |
|
812 |
|
813 |
|
814 | function generateFaviconTags (faviconPath) {
|
815 | if (!faviconPath) {
|
816 | return [];
|
817 | }
|
818 | return [{
|
819 | tagName: 'link',
|
820 | voidTag: true,
|
821 | meta: { plugin: 'html-webpack-plugin' },
|
822 | attributes: {
|
823 | rel: 'icon',
|
824 | href: faviconPath
|
825 | }
|
826 | }];
|
827 | }
|
828 |
|
829 | |
830 |
|
831 |
|
832 |
|
833 |
|
834 |
|
835 |
|
836 |
|
837 |
|
838 |
|
839 |
|
840 |
|
841 |
|
842 |
|
843 | function generateAssetGroups (assetTags, scriptTarget) {
|
844 |
|
845 | const result = {
|
846 | headTags: [
|
847 | ...assetTags.meta,
|
848 | ...assetTags.styles
|
849 | ],
|
850 | bodyTags: []
|
851 | };
|
852 |
|
853 |
|
854 | if (scriptTarget === 'body') {
|
855 | result.bodyTags.push(...assetTags.scripts);
|
856 | } else {
|
857 |
|
858 |
|
859 | const insertPosition = options.scriptLoading === 'blocking' ? result.headTags.length : assetTags.meta.length;
|
860 | result.headTags.splice(insertPosition, 0, ...assetTags.scripts);
|
861 | }
|
862 | return result;
|
863 | }
|
864 |
|
865 | |
866 |
|
867 |
|
868 |
|
869 |
|
870 |
|
871 |
|
872 | function prepareAssetTagGroupForRendering (assetTagGroup) {
|
873 | const xhtml = options.xhtml;
|
874 | return HtmlTagArray.from(assetTagGroup.map((assetTag) => {
|
875 | const copiedAssetTag = Object.assign({}, assetTag);
|
876 | copiedAssetTag.toString = function () {
|
877 | return htmlTagObjectToString(this, xhtml);
|
878 | };
|
879 | return copiedAssetTag;
|
880 | }));
|
881 | }
|
882 |
|
883 | |
884 |
|
885 |
|
886 |
|
887 |
|
888 |
|
889 |
|
890 |
|
891 |
|
892 |
|
893 |
|
894 |
|
895 |
|
896 |
|
897 | function injectAssetsIntoHtml (html, assets, assetTags) {
|
898 | const htmlRegExp = /(<html[^>]*>)/i;
|
899 | const headRegExp = /(<\/head\s*>)/i;
|
900 | const bodyRegExp = /(<\/body\s*>)/i;
|
901 | const body = assetTags.bodyTags.map((assetTagObject) => htmlTagObjectToString(assetTagObject, options.xhtml));
|
902 | const head = assetTags.headTags.map((assetTagObject) => htmlTagObjectToString(assetTagObject, options.xhtml));
|
903 |
|
904 | if (body.length) {
|
905 | if (bodyRegExp.test(html)) {
|
906 |
|
907 | html = html.replace(bodyRegExp, match => body.join('') + match);
|
908 | } else {
|
909 |
|
910 | html += body.join('');
|
911 | }
|
912 | }
|
913 |
|
914 | if (head.length) {
|
915 |
|
916 | if (!headRegExp.test(html)) {
|
917 | if (!htmlRegExp.test(html)) {
|
918 | html = '<head></head>' + html;
|
919 | } else {
|
920 | html = html.replace(htmlRegExp, match => match + '<head></head>');
|
921 | }
|
922 | }
|
923 |
|
924 |
|
925 | html = html.replace(headRegExp, match => head.join('') + match);
|
926 | }
|
927 |
|
928 |
|
929 | if (assets.manifest) {
|
930 | html = html.replace(/(<html[^>]*)(>)/i, (match, start, end) => {
|
931 |
|
932 | if (/\smanifest\s*=/.test(match)) {
|
933 | return match;
|
934 | }
|
935 | return start + ' manifest="' + assets.manifest + '"' + end;
|
936 | });
|
937 | }
|
938 | return html;
|
939 | }
|
940 |
|
941 | |
942 |
|
943 |
|
944 |
|
945 |
|
946 |
|
947 | function appendHash (url, hash) {
|
948 | if (!url) {
|
949 | return url;
|
950 | }
|
951 | return url + (url.indexOf('?') === -1 ? '?' : '&') + hash;
|
952 | }
|
953 |
|
954 | |
955 |
|
956 |
|
957 |
|
958 |
|
959 |
|
960 |
|
961 |
|
962 |
|
963 |
|
964 |
|
965 |
|
966 |
|
967 |
|
968 |
|
969 |
|
970 |
|
971 |
|
972 |
|
973 |
|
974 |
|
975 | function urlencodePath (filePath) {
|
976 |
|
977 |
|
978 |
|
979 |
|
980 |
|
981 | const queryStringStart = filePath.indexOf('?');
|
982 | const urlPath = queryStringStart === -1 ? filePath : filePath.substr(0, queryStringStart);
|
983 | const queryString = filePath.substr(urlPath.length);
|
984 |
|
985 | const encodedUrlPath = urlPath.split('/').map(encodeURIComponent).join('/');
|
986 | return encodedUrlPath + queryString;
|
987 | }
|
988 |
|
989 | |
990 |
|
991 |
|
992 |
|
993 |
|
994 |
|
995 |
|
996 | function getFullTemplatePath (template, context) {
|
997 | if (template === 'auto') {
|
998 | template = path.resolve(context, 'src/index.ejs');
|
999 | if (!fs.existsSync(template)) {
|
1000 | template = path.join(__dirname, 'default_index.ejs');
|
1001 | }
|
1002 | }
|
1003 |
|
1004 | if (template.indexOf('!') === -1) {
|
1005 | template = require.resolve('./lib/loader.js') + '!' + path.resolve(context, template);
|
1006 | }
|
1007 |
|
1008 | return template.replace(
|
1009 | /([!])([^/\\][^!?]+|[^/\\!?])($|\?[^!?\n]+$)/,
|
1010 | (match, prefix, filepath, postfix) => prefix + path.resolve(filepath) + postfix);
|
1011 | }
|
1012 |
|
1013 | |
1014 |
|
1015 |
|
1016 |
|
1017 |
|
1018 |
|
1019 |
|
1020 |
|
1021 |
|
1022 | function minifyHtml (html) {
|
1023 | if (typeof options.minify !== 'object') {
|
1024 | return html;
|
1025 | }
|
1026 | try {
|
1027 | return require('html-minifier-terser').minify(html, options.minify);
|
1028 | } catch (e) {
|
1029 | const isParseError = String(e.message).indexOf('Parse Error') === 0;
|
1030 | if (isParseError) {
|
1031 | e.message = 'html-webpack-plugin could not minify the generated output.\n' +
|
1032 | 'In production mode the html minifcation is enabled by default.\n' +
|
1033 | 'If you are not generating a valid html output please disable it manually.\n' +
|
1034 | 'You can do so by adding the following setting to your HtmlWebpackPlugin config:\n|\n|' +
|
1035 | ' minify: false\n|\n' +
|
1036 | 'See https://github.com/jantimon/html-webpack-plugin#options for details.\n\n' +
|
1037 | 'For parser dedicated bugs please create an issue here:\n' +
|
1038 | 'https://danielruf.github.io/html-minifier-terser/' +
|
1039 | '\n' + e.message;
|
1040 | }
|
1041 | throw e;
|
1042 | }
|
1043 | }
|
1044 |
|
1045 | |
1046 |
|
1047 |
|
1048 |
|
1049 | function getAssetFiles (assets) {
|
1050 | const files = _.uniq(Object.keys(assets).filter(assetType => assetType !== 'chunks' && assets[assetType]).reduce((files, assetType) => files.concat(assets[assetType]), []));
|
1051 | files.sort();
|
1052 | return files;
|
1053 | }
|
1054 | }
|
1055 |
|
1056 |
|
1057 |
|
1058 |
|
1059 |
|
1060 |
|
1061 |
|
1062 |
|
1063 |
|
1064 |
|
1065 |
|
1066 |
|
1067 |
|
1068 |
|
1069 |
|
1070 |
|
1071 |
|
1072 |
|
1073 |
|
1074 |
|
1075 |
|
1076 | function templateParametersGenerator (compilation, assets, assetTags, options) {
|
1077 | return {
|
1078 | compilation: compilation,
|
1079 | webpackConfig: compilation.options,
|
1080 | htmlWebpackPlugin: {
|
1081 | tags: assetTags,
|
1082 | files: assets,
|
1083 | options: options
|
1084 | }
|
1085 | };
|
1086 | }
|
1087 |
|
1088 |
|
1089 |
|
1090 |
|
1091 |
|
1092 | HtmlWebpackPlugin.version = 5;
|
1093 |
|
1094 |
|
1095 |
|
1096 |
|
1097 |
|
1098 |
|
1099 | HtmlWebpackPlugin.getHooks = getHtmlWebpackPluginHooks;
|
1100 | HtmlWebpackPlugin.createHtmlTagObject = createHtmlTagObject;
|
1101 |
|
1102 | module.exports = HtmlWebpackPlugin;
|