UNPKG

42.2 kBJavaScriptView Raw
1// @ts-check
2// Import types
3/** @typedef {import("./typings").HtmlTagObject} HtmlTagObject */
4/** @typedef {import("./typings").Options} HtmlWebpackOptions */
5/** @typedef {import("./typings").ProcessedOptions} ProcessedHtmlWebpackOptions */
6/** @typedef {import("./typings").TemplateParameter} TemplateParameter */
7/** @typedef {import("webpack/lib/Compiler.js")} WebpackCompiler */
8/** @typedef {import("webpack/lib/Compilation.js")} WebpackCompilation */
9'use strict';
10
11const promisify = require('util').promisify;
12
13const vm = require('vm');
14const fs = require('fs');
15const _ = require('lodash');
16const path = require('path');
17const { CachedChildCompilation } = require('./lib/cached-child-compiler');
18
19const { createHtmlTagObject, htmlTagObjectToString, HtmlTagArray } = require('./lib/html-tags');
20
21const prettyError = require('./lib/errors.js');
22const chunkSorter = require('./lib/chunksorter.js');
23const getHtmlWebpackPluginHooks = require('./lib/hooks.js').getHtmlWebpackPluginHooks;
24const { assert } = require('console');
25
26const fsReadFileAsync = promisify(fs.readFile);
27
28class HtmlWebpackPlugin {
29 /**
30 * @param {HtmlWebpackOptions} [options]
31 */
32 constructor (options) {
33 /** @type {HtmlWebpackOptions} */
34 this.userOptions = options || {};
35 this.version = HtmlWebpackPlugin.version;
36 }
37
38 apply (compiler) {
39 // Wait for configuration preset plugions to apply all configure webpack defaults
40 compiler.hooks.initialize.tap('HtmlWebpackPlugin', () => {
41 const userOptions = this.userOptions;
42
43 // Default options
44 /** @type {ProcessedHtmlWebpackOptions} */
45 const defaultOptions = {
46 template: 'auto',
47 templateContent: false,
48 templateParameters: templateParametersGenerator,
49 filename: 'index.html',
50 publicPath: userOptions.publicPath === undefined ? 'auto' : userOptions.publicPath,
51 hash: false,
52 inject: userOptions.scriptLoading === 'blocking' ? 'body' : 'head',
53 scriptLoading: 'defer',
54 compile: true,
55 favicon: false,
56 minify: 'auto',
57 cache: true,
58 showErrors: true,
59 chunks: 'all',
60 excludeChunks: [],
61 chunksSortMode: 'auto',
62 meta: {},
63 base: false,
64 title: 'Webpack App',
65 xhtml: false
66 };
67
68 /** @type {ProcessedHtmlWebpackOptions} */
69 const options = Object.assign(defaultOptions, userOptions);
70 this.options = options;
71
72 // Assert correct option spelling
73 assert(options.scriptLoading === 'defer' || options.scriptLoading === 'blocking', 'scriptLoading needs to be set to "defer" or "blocking');
74 assert(options.inject === true || options.inject === false || options.inject === 'head' || options.inject === 'body', 'inject needs to be set to true, false, "head" or "body');
75
76 // Default metaOptions if no template is provided
77 if (!userOptions.template && options.templateContent === false && options.meta) {
78 const defaultMeta = {
79 // From https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag
80 viewport: 'width=device-width, initial-scale=1'
81 };
82 options.meta = Object.assign({}, options.meta, defaultMeta, userOptions.meta);
83 }
84
85 // entryName to fileName conversion function
86 const userOptionFilename = userOptions.filename || defaultOptions.filename;
87 const filenameFunction = typeof userOptionFilename === 'function'
88 ? userOptionFilename
89 // Replace '[name]' with entry name
90 : (entryName) => userOptionFilename.replace(/\[name\]/g, entryName);
91
92 /** output filenames for the given entry names */
93 const entryNames = Object.keys(compiler.options.entry);
94 const outputFileNames = new Set((entryNames.length ? entryNames : ['main']).map(filenameFunction));
95
96 /** Option for every entry point */
97 const entryOptions = Array.from(outputFileNames).map((filename) => ({
98 ...options,
99 filename
100 }));
101
102 // Hook all options into the webpack compiler
103 entryOptions.forEach((instanceOptions) => {
104 hookIntoCompiler(compiler, instanceOptions, this);
105 });
106 });
107 }
108
109 /**
110 * Once webpack is done with compiling the template into a NodeJS code this function
111 * evaluates it to generate the html result
112 *
113 * The evaluateCompilationResult is only a class function to allow spying during testing.
114 * Please change that in a further refactoring
115 *
116 * @param {string} source
117 * @param {string} templateFilename
118 * @returns {Promise<string | (() => string | Promise<string>)>}
119 */
120 evaluateCompilationResult (source, publicPath, templateFilename) {
121 if (!source) {
122 return Promise.reject(new Error('The child compilation didn\'t provide a result'));
123 }
124 // The LibraryTemplatePlugin stores the template result in a local variable.
125 // By adding it to the end the value gets extracted during evaluation
126 if (source.indexOf('HTML_WEBPACK_PLUGIN_RESULT') >= 0) {
127 source += ';\nHTML_WEBPACK_PLUGIN_RESULT';
128 }
129 const templateWithoutLoaders = templateFilename.replace(/^.+!/, '').replace(/\?.+$/, '');
130 const vmContext = vm.createContext({
131 ...global,
132 HTML_WEBPACK_PLUGIN: true,
133 require: require,
134 htmlWebpackPluginPublicPath: publicPath,
135 URL: require('url').URL,
136 __filename: templateWithoutLoaders
137 });
138 const vmScript = new vm.Script(source, { filename: templateWithoutLoaders });
139 // Evaluate code and cast to string
140 let newSource;
141 try {
142 newSource = vmScript.runInContext(vmContext);
143 } catch (e) {
144 return Promise.reject(e);
145 }
146 if (typeof newSource === 'object' && newSource.__esModule && newSource.default) {
147 newSource = newSource.default;
148 }
149 return typeof newSource === 'string' || typeof newSource === 'function'
150 ? Promise.resolve(newSource)
151 : Promise.reject(new Error('The loader "' + templateWithoutLoaders + '" didn\'t return html.'));
152 }
153}
154
155/**
156 * connect the html-webpack-plugin to the webpack compiler lifecycle hooks
157 *
158 * @param {import('webpack').Compiler} compiler
159 * @param {ProcessedHtmlWebpackOptions} options
160 * @param {HtmlWebpackPlugin} plugin
161 */
162function hookIntoCompiler (compiler, options, plugin) {
163 const webpack = compiler.webpack;
164 // Instance variables to keep caching information
165 // for multiple builds
166 let assetJson;
167 /**
168 * store the previous generated asset to emit them even if the content did not change
169 * to support watch mode for third party plugins like the clean-webpack-plugin or the compression plugin
170 * @type {Array<{html: string, name: string}>}
171 */
172 let previousEmittedAssets = [];
173
174 options.template = getFullTemplatePath(options.template, compiler.context);
175
176 // Inject child compiler plugin
177 const childCompilerPlugin = new CachedChildCompilation(compiler);
178 if (!options.templateContent) {
179 childCompilerPlugin.addEntry(options.template);
180 }
181
182 // convert absolute filename into relative so that webpack can
183 // generate it at correct location
184 const filename = options.filename;
185 if (path.resolve(filename) === path.normalize(filename)) {
186 const outputPath = /** @type {string} - Once initialized the path is always a string */(compiler.options.output.path);
187 options.filename = path.relative(outputPath, filename);
188 }
189
190 // Check if webpack is running in production mode
191 // @see https://github.com/webpack/webpack/blob/3366421f1784c449f415cda5930a8e445086f688/lib/WebpackOptionsDefaulter.js#L12-L14
192 const isProductionLikeMode = compiler.options.mode === 'production' || !compiler.options.mode;
193
194 const minify = options.minify;
195 if (minify === true || (minify === 'auto' && isProductionLikeMode)) {
196 /** @type { import('html-minifier-terser').Options } */
197 options.minify = {
198 // https://www.npmjs.com/package/html-minifier-terser#options-quick-reference
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 * Hook into the webpack compilation
212 * @param {WebpackCompilation} compilation
213 */
214 (compilation) => {
215 compilation.hooks.processAssets.tapAsync(
216 {
217 name: 'HtmlWebpackPlugin',
218 stage:
219 /**
220 * Generate the html after minification and dev tooling is done
221 */
222 webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
223 },
224 /**
225 * Hook into the process assets hook
226 * @param {WebpackCompilation} compilationAssets
227 * @param {(err?: Error) => void} callback
228 */
229 (compilationAssets, callback) => {
230 // Get all entry point names for this html file
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 // If the child compilation was not executed during a previous main compile run
244 // it is a cached result
245 const isCompilationCached = templateResult.mainCompilationHash !== compilation.hash;
246
247 /** The public path used inside the html file */
248 const htmlPublicPath = getPublicPath(compilation, options.filename, options.publicPath);
249
250 /** Generated file paths from the entry point names */
251 const assets = htmlWebpackPluginAssets(compilation, sortedEntryNames, htmlPublicPath);
252
253 // If the template and the assets did not change we don't have to emit the html
254 const newAssetJson = JSON.stringify(getAssetFiles(assets));
255 if (isCompilationCached && options.cache && assetJson === newAssetJson) {
256 previousEmittedAssets.forEach(({ name, html }) => {
257 compilation.emitAsset(name, new webpack.sources.RawSource(html, false));
258 });
259 return callback();
260 } else {
261 previousEmittedAssets = [];
262 assetJson = newAssetJson;
263 }
264
265 // The html-webpack plugin uses a object representation for the html-tags which will be injected
266 // to allow altering them more easily
267 // Just before they are converted a third-party-plugin author might change the order and content
268 const assetsPromise = getFaviconPublicPath(options.favicon, compilation, assets.publicPath)
269 .then((faviconPath) => {
270 assets.favicon = faviconPath;
271 return getHtmlWebpackPluginHooks(compilation).beforeAssetTagGeneration.promise({
272 assets: assets,
273 outputName: options.filename,
274 plugin: plugin
275 });
276 });
277
278 // Turn the js and css paths into grouped HtmlTagObjects
279 const assetTagGroupsPromise = assetsPromise
280 // And allow third-party-plugin authors to reorder and change the assetTags before they are grouped
281 .then(({ assets }) => getHtmlWebpackPluginHooks(compilation).alterAssetTags.promise({
282 assetTags: {
283 scripts: generatedScriptTags(assets.js),
284 styles: generateStyleTags(assets.css),
285 meta: [
286 ...generateBaseTag(options.base),
287 ...generatedMetaTags(options.meta),
288 ...generateFaviconTags(assets.favicon)
289 ]
290 },
291 outputName: options.filename,
292 publicPath: htmlPublicPath,
293 plugin: plugin
294 }))
295 .then(({ assetTags }) => {
296 // Inject scripts to body unless it set explicitly to head
297 const scriptTarget = options.inject === 'head' ||
298 (options.inject !== 'body' && options.scriptLoading !== 'blocking') ? 'head' : 'body';
299 // Group assets to `head` and `body` tag arrays
300 const assetGroups = generateAssetGroups(assetTags, scriptTarget);
301 // Allow third-party-plugin authors to reorder and change the assetTags once they are grouped
302 return getHtmlWebpackPluginHooks(compilation).alterAssetTagGroups.promise({
303 headTags: assetGroups.headTags,
304 bodyTags: assetGroups.bodyTags,
305 outputName: options.filename,
306 publicPath: htmlPublicPath,
307 plugin: plugin
308 });
309 });
310
311 // Turn the compiled template into a nodejs function or into a nodejs string
312 const templateEvaluationPromise = Promise.resolve()
313 .then(() => {
314 if ('error' in templateResult) {
315 return options.showErrors ? prettyError(templateResult.error, compiler.context).toHtml() : 'ERROR';
316 }
317 // Allow to use a custom function / string instead
318 if (options.templateContent !== false) {
319 return options.templateContent;
320 }
321 // Once everything is compiled evaluate the html factory
322 // and replace it with its content
323 return ('compiledEntry' in templateResult)
324 ? plugin.evaluateCompilationResult(templateResult.compiledEntry.content, htmlPublicPath, options.template)
325 : Promise.reject(new Error('Child compilation contained no compiledEntry'));
326 });
327 const templateExectutionPromise = Promise.all([assetsPromise, assetTagGroupsPromise, templateEvaluationPromise])
328 // Execute the template
329 .then(([assetsHookResult, assetTags, compilationResult]) => typeof compilationResult !== 'function'
330 ? compilationResult
331 : executeTemplate(compilationResult, assetsHookResult.assets, { headTags: assetTags.headTags, bodyTags: assetTags.bodyTags }, compilation));
332
333 const injectedHtmlPromise = Promise.all([assetTagGroupsPromise, templateExectutionPromise])
334 // Allow plugins to change the html before assets are injected
335 .then(([assetTags, html]) => {
336 const pluginArgs = { html, headTags: assetTags.headTags, bodyTags: assetTags.bodyTags, plugin: plugin, outputName: options.filename };
337 return getHtmlWebpackPluginHooks(compilation).afterTemplateExecution.promise(pluginArgs);
338 })
339 .then(({ html, headTags, bodyTags }) => {
340 return postProcessHtml(html, assets, { headTags, bodyTags });
341 });
342
343 const emitHtmlPromise = injectedHtmlPromise
344 // Allow plugins to change the html after assets are injected
345 .then((html) => {
346 const pluginArgs = { html, plugin: plugin, outputName: options.filename };
347 return getHtmlWebpackPluginHooks(compilation).beforeEmit.promise(pluginArgs)
348 .then(result => result.html);
349 })
350 .catch(err => {
351 // In case anything went wrong the promise is resolved
352 // with the error message and an error is logged
353 compilation.errors.push(prettyError(err, compiler.context).toString());
354 return options.showErrors ? prettyError(err, compiler.context).toHtml() : 'ERROR';
355 })
356 .then(html => {
357 const filename = options.filename.replace(/\[templatehash([^\]]*)\]/g, require('util').deprecate(
358 (match, options) => `[contenthash${options}]`,
359 '[templatehash] is now [contenthash]')
360 );
361 const replacedFilename = replacePlaceholdersInFilename(filename, html, compilation);
362 // Add the evaluated html code to the webpack assets
363 compilation.emitAsset(replacedFilename.path, new webpack.sources.RawSource(html, false), replacedFilename.info);
364 previousEmittedAssets.push({ name: replacedFilename.path, html });
365 return replacedFilename.path;
366 })
367 .then((finalOutputName) => getHtmlWebpackPluginHooks(compilation).afterEmit.promise({
368 outputName: finalOutputName,
369 plugin: plugin
370 }).catch(err => {
371 console.error(err);
372 return null;
373 }).then(() => null));
374
375 // Once all files are added to the webpack compilation
376 // let the webpack compiler continue
377 emitHtmlPromise.then(() => {
378 callback();
379 });
380 });
381 });
382
383 /**
384 * Generate the template parameters for the template function
385 * @param {WebpackCompilation} compilation
386 * @param {{
387 publicPath: string,
388 js: Array<string>,
389 css: Array<string>,
390 manifest?: string,
391 favicon?: string
392 }} assets
393 * @param {{
394 headTags: HtmlTagObject[],
395 bodyTags: HtmlTagObject[]
396 }} assetTags
397 * @returns {Promise<{[key: any]: any}>}
398 */
399 function getTemplateParameters (compilation, assets, assetTags) {
400 const templateParameters = options.templateParameters;
401 if (templateParameters === false) {
402 return Promise.resolve({});
403 }
404 if (typeof templateParameters !== 'function' && typeof templateParameters !== 'object') {
405 throw new Error('templateParameters has to be either a function or an object');
406 }
407 const templateParameterFunction = typeof templateParameters === 'function'
408 // A custom function can overwrite the entire template parameter preparation
409 ? templateParameters
410 // If the template parameters is an object merge it with the default values
411 : (compilation, assets, assetTags, options) => Object.assign({},
412 templateParametersGenerator(compilation, assets, assetTags, options),
413 templateParameters
414 );
415 const preparedAssetTags = {
416 headTags: prepareAssetTagGroupForRendering(assetTags.headTags),
417 bodyTags: prepareAssetTagGroupForRendering(assetTags.bodyTags)
418 };
419 return Promise
420 .resolve()
421 .then(() => templateParameterFunction(compilation, assets, preparedAssetTags, options));
422 }
423
424 /**
425 * This function renders the actual html by executing the template function
426 *
427 * @param {(templateParameters) => string | Promise<string>} templateFunction
428 * @param {{
429 publicPath: string,
430 js: Array<string>,
431 css: Array<string>,
432 manifest?: string,
433 favicon?: string
434 }} assets
435 * @param {{
436 headTags: HtmlTagObject[],
437 bodyTags: HtmlTagObject[]
438 }} assetTags
439 * @param {WebpackCompilation} compilation
440 *
441 * @returns Promise<string>
442 */
443 function executeTemplate (templateFunction, assets, assetTags, compilation) {
444 // Template processing
445 const templateParamsPromise = getTemplateParameters(compilation, assets, assetTags);
446 return templateParamsPromise.then((templateParams) => {
447 try {
448 // If html is a promise return the promise
449 // If html is a string turn it into a promise
450 return templateFunction(templateParams);
451 } catch (e) {
452 compilation.errors.push(new Error('Template execution failed: ' + e));
453 return Promise.reject(e);
454 }
455 });
456 }
457
458 /**
459 * Html Post processing
460 *
461 * @param {any} html
462 * The input html
463 * @param {any} assets
464 * @param {{
465 headTags: HtmlTagObject[],
466 bodyTags: HtmlTagObject[]
467 }} assetTags
468 * The asset tags to inject
469 *
470 * @returns {Promise<string>}
471 */
472 function postProcessHtml (html, assets, assetTags) {
473 if (typeof html !== 'string') {
474 return Promise.reject(new Error('Expected html to be a string but got ' + JSON.stringify(html)));
475 }
476 const htmlAfterInjection = options.inject
477 ? injectAssetsIntoHtml(html, assets, assetTags)
478 : html;
479 const htmlAfterMinification = minifyHtml(htmlAfterInjection);
480 return Promise.resolve(htmlAfterMinification);
481 }
482
483 /*
484 * Pushes the content of the given filename to the compilation assets
485 * @param {string} filename
486 * @param {WebpackCompilation} compilation
487 *
488 * @returns {string} file basename
489 */
490 function addFileToAssets (filename, compilation) {
491 filename = path.resolve(compilation.compiler.context, filename);
492 return fsReadFileAsync(filename)
493 .then(source => new webpack.sources.RawSource(source, false))
494 .catch(() => Promise.reject(new Error('HtmlWebpackPlugin: could not load file ' + filename)))
495 .then(rawSource => {
496 const basename = path.basename(filename);
497 compilation.fileDependencies.add(filename);
498 compilation.emitAsset(basename, rawSource);
499 return basename;
500 });
501 }
502
503 /**
504 * Replace [contenthash] in filename
505 *
506 * @see https://survivejs.com/webpack/optimizing/adding-hashes-to-filenames/
507 *
508 * @param {string} filename
509 * @param {string|Buffer} fileContent
510 * @param {WebpackCompilation} compilation
511 * @returns {{ path: string, info: {} }}
512 */
513 function replacePlaceholdersInFilename (filename, fileContent, compilation) {
514 if (/\[\\*([\w:]+)\\*\]/i.test(filename) === false) {
515 return { path: filename, info: {} };
516 }
517 const hash = compiler.webpack.util.createHash(compilation.outputOptions.hashFunction);
518 hash.update(fileContent);
519 if (compilation.outputOptions.hashSalt) {
520 hash.update(compilation.outputOptions.hashSalt);
521 }
522 const contentHash = hash.digest(compilation.outputOptions.hashDigest).slice(0, compilation.outputOptions.hashDigestLength);
523 return compilation.getPathWithInfo(
524 filename,
525 {
526 contentHash,
527 chunk: {
528 hash: contentHash,
529 contentHash
530 }
531 }
532 );
533 }
534
535 /**
536 * Helper to sort chunks
537 * @param {string[]} entryNames
538 * @param {string|((entryNameA: string, entryNameB: string) => number)} sortMode
539 * @param {WebpackCompilation} compilation
540 */
541 function sortEntryChunks (entryNames, sortMode, compilation) {
542 // Custom function
543 if (typeof sortMode === 'function') {
544 return entryNames.sort(sortMode);
545 }
546 // Check if the given sort mode is a valid chunkSorter sort mode
547 if (typeof chunkSorter[sortMode] !== 'undefined') {
548 return chunkSorter[sortMode](entryNames, compilation, options);
549 }
550 throw new Error('"' + sortMode + '" is not a valid chunk sort mode');
551 }
552
553 /**
554 * Return all chunks from the compilation result which match the exclude and include filters
555 * @param {any} chunks
556 * @param {string[]|'all'} includedChunks
557 * @param {string[]} excludedChunks
558 */
559 function filterChunks (chunks, includedChunks, excludedChunks) {
560 return chunks.filter(chunkName => {
561 // Skip if the chunks should be filtered and the given chunk was not added explicity
562 if (Array.isArray(includedChunks) && includedChunks.indexOf(chunkName) === -1) {
563 return false;
564 }
565 // Skip if the chunks should be filtered and the given chunk was excluded explicity
566 if (Array.isArray(excludedChunks) && excludedChunks.indexOf(chunkName) !== -1) {
567 return false;
568 }
569 // Add otherwise
570 return true;
571 });
572 }
573
574 /**
575 * Generate the relative or absolute base url to reference images, css, and javascript files
576 * from within the html file - the publicPath
577 *
578 * @param {WebpackCompilation} compilation
579 * @param {string} childCompilationOutputName
580 * @param {string | 'auto'} customPublicPath
581 * @returns {string}
582 */
583 function getPublicPath (compilation, childCompilationOutputName, customPublicPath) {
584 const compilationHash = compilation.hash;
585
586 /**
587 * @type {string} the configured public path to the asset root
588 * if a path publicPath is set in the current webpack config use it otherwise
589 * fallback to a relative path
590 */
591 const webpackPublicPath = compilation.getAssetPath(compilation.outputOptions.publicPath, { hash: compilationHash });
592
593 // Webpack 5 introduced "auto" as default value
594 const isPublicPathDefined = webpackPublicPath !== 'auto';
595
596 let publicPath =
597 // If the html-webpack-plugin options contain a custom public path uset it
598 customPublicPath !== 'auto'
599 ? customPublicPath
600 : (isPublicPathDefined
601 // If a hard coded public path exists use it
602 ? webpackPublicPath
603 // If no public path was set get a relative url path
604 : path.relative(path.resolve(compilation.options.output.path, path.dirname(childCompilationOutputName)), compilation.options.output.path)
605 .split(path.sep).join('/')
606 );
607
608 if (publicPath.length && publicPath.substr(-1, 1) !== '/') {
609 publicPath += '/';
610 }
611
612 return publicPath;
613 }
614
615 /**
616 * The htmlWebpackPluginAssets extracts the asset information of a webpack compilation
617 * for all given entry names
618 * @param {WebpackCompilation} compilation
619 * @param {string[]} entryNames
620 * @param {string | 'auto'} publicPath
621 * @returns {{
622 publicPath: string,
623 js: Array<string>,
624 css: Array<string>,
625 manifest?: string,
626 favicon?: string
627 }}
628 */
629 function htmlWebpackPluginAssets (compilation, entryNames, publicPath) {
630 const compilationHash = compilation.hash;
631 /**
632 * @type {{
633 publicPath: string,
634 js: Array<string>,
635 css: Array<string>,
636 manifest?: string,
637 favicon?: string
638 }}
639 */
640 const assets = {
641 // The public path
642 publicPath,
643 // Will contain all js and mjs files
644 js: [],
645 // Will contain all css files
646 css: [],
647 // Will contain the html5 appcache manifest files if it exists
648 manifest: Object.keys(compilation.assets).find(assetFile => path.extname(assetFile) === '.appcache'),
649 // Favicon
650 favicon: undefined
651 };
652
653 // Append a hash for cache busting
654 if (options.hash && assets.manifest) {
655 assets.manifest = appendHash(assets.manifest, compilationHash);
656 }
657
658 // Extract paths to .js, .mjs and .css files from the current compilation
659 const entryPointPublicPathMap = {};
660 const extensionRegexp = /\.(css|js|mjs)(\?|$)/;
661 for (let i = 0; i < entryNames.length; i++) {
662 const entryName = entryNames[i];
663 /** entryPointUnfilteredFiles - also includes hot module update files */
664 const entryPointUnfilteredFiles = compilation.entrypoints.get(entryName).getFiles();
665
666 const entryPointFiles = entryPointUnfilteredFiles.filter((chunkFile) => {
667 // compilation.getAsset was introduced in webpack 4.4.0
668 // once the support pre webpack 4.4.0 is dropped please
669 // remove the following guard:
670 const asset = compilation.getAsset && compilation.getAsset(chunkFile);
671 if (!asset) {
672 return true;
673 }
674 // Prevent hot-module files from being included:
675 const assetMetaInformation = asset.info || {};
676 return !(assetMetaInformation.hotModuleReplacement || assetMetaInformation.development);
677 });
678
679 // Prepend the publicPath and append the hash depending on the
680 // webpack.output.publicPath and hashOptions
681 // E.g. bundle.js -> /bundle.js?hash
682 const entryPointPublicPaths = entryPointFiles
683 .map(chunkFile => {
684 const entryPointPublicPath = publicPath + urlencodePath(chunkFile);
685 return options.hash
686 ? appendHash(entryPointPublicPath, compilationHash)
687 : entryPointPublicPath;
688 });
689
690 entryPointPublicPaths.forEach((entryPointPublicPath) => {
691 const extMatch = extensionRegexp.exec(entryPointPublicPath);
692 // Skip if the public path is not a .css, .mjs or .js file
693 if (!extMatch) {
694 return;
695 }
696 // Skip if this file is already known
697 // (e.g. because of common chunk optimizations)
698 if (entryPointPublicPathMap[entryPointPublicPath]) {
699 return;
700 }
701 entryPointPublicPathMap[entryPointPublicPath] = true;
702 // ext will contain .js or .css, because .mjs recognizes as .js
703 const ext = extMatch[1] === 'mjs' ? 'js' : extMatch[1];
704 assets[ext].push(entryPointPublicPath);
705 });
706 }
707 return assets;
708 }
709
710 /**
711 * Converts a favicon file from disk to a webpack resource
712 * and returns the url to the resource
713 *
714 * @param {string|false} faviconFilePath
715 * @param {WebpackCompilation} compilation
716 * @param {string} publicPath
717 * @returns {Promise<string|undefined>}
718 */
719 function getFaviconPublicPath (faviconFilePath, compilation, publicPath) {
720 if (!faviconFilePath) {
721 return Promise.resolve(undefined);
722 }
723 return addFileToAssets(faviconFilePath, compilation)
724 .then((faviconName) => {
725 const faviconPath = publicPath + faviconName;
726 if (options.hash) {
727 return appendHash(faviconPath, compilation.hash);
728 }
729 return faviconPath;
730 });
731 }
732
733 /**
734 * Generate all tags script for the given file paths
735 * @param {Array<string>} jsAssets
736 * @returns {Array<HtmlTagObject>}
737 */
738 function generatedScriptTags (jsAssets) {
739 return jsAssets.map(scriptAsset => ({
740 tagName: 'script',
741 voidTag: false,
742 meta: { plugin: 'html-webpack-plugin' },
743 attributes: {
744 defer: options.scriptLoading !== 'blocking',
745 src: scriptAsset
746 }
747 }));
748 }
749
750 /**
751 * Generate all style tags for the given file paths
752 * @param {Array<string>} cssAssets
753 * @returns {Array<HtmlTagObject>}
754 */
755 function generateStyleTags (cssAssets) {
756 return cssAssets.map(styleAsset => ({
757 tagName: 'link',
758 voidTag: true,
759 meta: { plugin: 'html-webpack-plugin' },
760 attributes: {
761 href: styleAsset,
762 rel: 'stylesheet'
763 }
764 }));
765 }
766
767 /**
768 * Generate an optional base tag
769 * @param { false
770 | string
771 | {[attributeName: string]: string} // attributes e.g. { href:"http://example.com/page.html" target:"_blank" }
772 } baseOption
773 * @returns {Array<HtmlTagObject>}
774 */
775 function generateBaseTag (baseOption) {
776 if (baseOption === false) {
777 return [];
778 } else {
779 return [{
780 tagName: 'base',
781 voidTag: true,
782 meta: { plugin: 'html-webpack-plugin' },
783 attributes: (typeof baseOption === 'string') ? {
784 href: baseOption
785 } : baseOption
786 }];
787 }
788 }
789
790 /**
791 * Generate all meta tags for the given meta configuration
792 * @param {false | {
793 [name: string]:
794 false // disabled
795 | string // name content pair e.g. {viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no'}`
796 | {[attributeName: string]: string|boolean} // custom properties e.g. { name:"viewport" content:"width=500, initial-scale=1" }
797 }} metaOptions
798 * @returns {Array<HtmlTagObject>}
799 */
800 function generatedMetaTags (metaOptions) {
801 if (metaOptions === false) {
802 return [];
803 }
804 // Make tags self-closing in case of xhtml
805 // Turn { "viewport" : "width=500, initial-scale=1" } into
806 // [{ name:"viewport" content:"width=500, initial-scale=1" }]
807 const metaTagAttributeObjects = Object.keys(metaOptions)
808 .map((metaName) => {
809 const metaTagContent = metaOptions[metaName];
810 return (typeof metaTagContent === 'string') ? {
811 name: metaName,
812 content: metaTagContent
813 } : metaTagContent;
814 })
815 .filter((attribute) => attribute !== false);
816 // Turn [{ name:"viewport" content:"width=500, initial-scale=1" }] into
817 // the html-webpack-plugin tag structure
818 return metaTagAttributeObjects.map((metaTagAttributes) => {
819 if (metaTagAttributes === false) {
820 throw new Error('Invalid meta tag');
821 }
822 return {
823 tagName: 'meta',
824 voidTag: true,
825 meta: { plugin: 'html-webpack-plugin' },
826 attributes: metaTagAttributes
827 };
828 });
829 }
830
831 /**
832 * Generate a favicon tag for the given file path
833 * @param {string| undefined} faviconPath
834 * @returns {Array<HtmlTagObject>}
835 */
836 function generateFaviconTags (faviconPath) {
837 if (!faviconPath) {
838 return [];
839 }
840 return [{
841 tagName: 'link',
842 voidTag: true,
843 meta: { plugin: 'html-webpack-plugin' },
844 attributes: {
845 rel: 'icon',
846 href: faviconPath
847 }
848 }];
849 }
850
851 /**
852 * Group assets to head and bottom tags
853 *
854 * @param {{
855 scripts: Array<HtmlTagObject>;
856 styles: Array<HtmlTagObject>;
857 meta: Array<HtmlTagObject>;
858 }} assetTags
859 * @param {"body" | "head"} scriptTarget
860 * @returns {{
861 headTags: Array<HtmlTagObject>;
862 bodyTags: Array<HtmlTagObject>;
863 }}
864 */
865 function generateAssetGroups (assetTags, scriptTarget) {
866 /** @type {{ headTags: Array<HtmlTagObject>; bodyTags: Array<HtmlTagObject>; }} */
867 const result = {
868 headTags: [
869 ...assetTags.meta,
870 ...assetTags.styles
871 ],
872 bodyTags: []
873 };
874 // Add script tags to head or body depending on
875 // the htmlPluginOptions
876 if (scriptTarget === 'body') {
877 result.bodyTags.push(...assetTags.scripts);
878 } else {
879 // If script loading is blocking add the scripts to the end of the head
880 // If script loading is non-blocking add the scripts infront of the css files
881 const insertPosition = options.scriptLoading === 'blocking' ? result.headTags.length : assetTags.meta.length;
882 result.headTags.splice(insertPosition, 0, ...assetTags.scripts);
883 }
884 return result;
885 }
886
887 /**
888 * Add toString methods for easier rendering
889 * inside the template
890 *
891 * @param {Array<HtmlTagObject>} assetTagGroup
892 * @returns {Array<HtmlTagObject>}
893 */
894 function prepareAssetTagGroupForRendering (assetTagGroup) {
895 const xhtml = options.xhtml;
896 return HtmlTagArray.from(assetTagGroup.map((assetTag) => {
897 const copiedAssetTag = Object.assign({}, assetTag);
898 copiedAssetTag.toString = function () {
899 return htmlTagObjectToString(this, xhtml);
900 };
901 return copiedAssetTag;
902 }));
903 }
904
905 /**
906 * Injects the assets into the given html string
907 *
908 * @param {string} html
909 * The input html
910 * @param {any} assets
911 * @param {{
912 headTags: HtmlTagObject[],
913 bodyTags: HtmlTagObject[]
914 }} assetTags
915 * The asset tags to inject
916 *
917 * @returns {string}
918 */
919 function injectAssetsIntoHtml (html, assets, assetTags) {
920 const htmlRegExp = /(<html[^>]*>)/i;
921 const headRegExp = /(<\/head\s*>)/i;
922 const bodyRegExp = /(<\/body\s*>)/i;
923 const body = assetTags.bodyTags.map((assetTagObject) => htmlTagObjectToString(assetTagObject, options.xhtml));
924 const head = assetTags.headTags.map((assetTagObject) => htmlTagObjectToString(assetTagObject, options.xhtml));
925
926 if (body.length) {
927 if (bodyRegExp.test(html)) {
928 // Append assets to body element
929 html = html.replace(bodyRegExp, match => body.join('') + match);
930 } else {
931 // Append scripts to the end of the file if no <body> element exists:
932 html += body.join('');
933 }
934 }
935
936 if (head.length) {
937 // Create a head tag if none exists
938 if (!headRegExp.test(html)) {
939 if (!htmlRegExp.test(html)) {
940 html = '<head></head>' + html;
941 } else {
942 html = html.replace(htmlRegExp, match => match + '<head></head>');
943 }
944 }
945
946 // Append assets to head element
947 html = html.replace(headRegExp, match => head.join('') + match);
948 }
949
950 // Inject manifest into the opening html tag
951 if (assets.manifest) {
952 html = html.replace(/(<html[^>]*)(>)/i, (match, start, end) => {
953 // Append the manifest only if no manifest was specified
954 if (/\smanifest\s*=/.test(match)) {
955 return match;
956 }
957 return start + ' manifest="' + assets.manifest + '"' + end;
958 });
959 }
960 return html;
961 }
962
963 /**
964 * Appends a cache busting hash to the query string of the url
965 * E.g. http://localhost:8080/ -> http://localhost:8080/?50c9096ba6183fd728eeb065a26ec175
966 * @param {string} url
967 * @param {string} hash
968 */
969 function appendHash (url, hash) {
970 if (!url) {
971 return url;
972 }
973 return url + (url.indexOf('?') === -1 ? '?' : '&') + hash;
974 }
975
976 /**
977 * Encode each path component using `encodeURIComponent` as files can contain characters
978 * which needs special encoding in URLs like `+ `.
979 *
980 * Valid filesystem characters which need to be encoded for urls:
981 *
982 * # pound, % percent, & ampersand, { left curly bracket, } right curly bracket,
983 * \ back slash, < left angle bracket, > right angle bracket, * asterisk, ? question mark,
984 * blank spaces, $ dollar sign, ! exclamation point, ' single quotes, " double quotes,
985 * : colon, @ at sign, + plus sign, ` backtick, | pipe, = equal sign
986 *
987 * However the query string must not be encoded:
988 *
989 * fo:demonstration-path/very fancy+name.js?path=/home?value=abc&value=def#zzz
990 * ^ ^ ^ ^ ^ ^ ^ ^^ ^ ^ ^ ^ ^
991 * | | | | | | | || | | | | |
992 * encoded | | encoded | | || | | | | |
993 * ignored ignored ignored ignored ignored
994 *
995 * @param {string} filePath
996 */
997 function urlencodePath (filePath) {
998 // People use the filepath in quite unexpected ways.
999 // Try to extract the first querystring of the url:
1000 //
1001 // some+path/demo.html?value=abc?def
1002 //
1003 const queryStringStart = filePath.indexOf('?');
1004 const urlPath = queryStringStart === -1 ? filePath : filePath.substr(0, queryStringStart);
1005 const queryString = filePath.substr(urlPath.length);
1006 // Encode all parts except '/' which are not part of the querystring:
1007 const encodedUrlPath = urlPath.split('/').map(encodeURIComponent).join('/');
1008 return encodedUrlPath + queryString;
1009 }
1010
1011 /**
1012 * Helper to return the absolute template path with a fallback loader
1013 * @param {string} template
1014 * The path to the template e.g. './index.html'
1015 * @param {string} context
1016 * The webpack base resolution path for relative paths e.g. process.cwd()
1017 */
1018 function getFullTemplatePath (template, context) {
1019 if (template === 'auto') {
1020 template = path.resolve(context, 'src/index.ejs');
1021 if (!fs.existsSync(template)) {
1022 template = path.join(__dirname, 'default_index.ejs');
1023 }
1024 }
1025 // If the template doesn't use a loader use the lodash template loader
1026 if (template.indexOf('!') === -1) {
1027 template = require.resolve('./lib/loader.js') + '!' + path.resolve(context, template);
1028 }
1029 // Resolve template path
1030 return template.replace(
1031 /([!])([^/\\][^!?]+|[^/\\!?])($|\?[^!?\n]+$)/,
1032 (match, prefix, filepath, postfix) => prefix + path.resolve(filepath) + postfix);
1033 }
1034
1035 /**
1036 * Minify the given string using html-minifier-terser
1037 *
1038 * As this is a breaking change to html-webpack-plugin 3.x
1039 * provide an extended error message to explain how to get back
1040 * to the old behaviour
1041 *
1042 * @param {string} html
1043 */
1044 function minifyHtml (html) {
1045 if (typeof options.minify !== 'object') {
1046 return html;
1047 }
1048 try {
1049 return require('html-minifier-terser').minify(html, options.minify);
1050 } catch (e) {
1051 const isParseError = String(e.message).indexOf('Parse Error') === 0;
1052 if (isParseError) {
1053 e.message = 'html-webpack-plugin could not minify the generated output.\n' +
1054 'In production mode the html minifcation is enabled by default.\n' +
1055 'If you are not generating a valid html output please disable it manually.\n' +
1056 'You can do so by adding the following setting to your HtmlWebpackPlugin config:\n|\n|' +
1057 ' minify: false\n|\n' +
1058 'See https://github.com/jantimon/html-webpack-plugin#options for details.\n\n' +
1059 'For parser dedicated bugs please create an issue here:\n' +
1060 'https://danielruf.github.io/html-minifier-terser/' +
1061 '\n' + e.message;
1062 }
1063 throw e;
1064 }
1065 }
1066
1067 /**
1068 * Helper to return a sorted unique array of all asset files out of the
1069 * asset object
1070 */
1071 function getAssetFiles (assets) {
1072 const files = _.uniq(Object.keys(assets).filter(assetType => assetType !== 'chunks' && assets[assetType]).reduce((files, assetType) => files.concat(assets[assetType]), []));
1073 files.sort();
1074 return files;
1075 }
1076}
1077
1078/**
1079 * The default for options.templateParameter
1080 * Generate the template parameters
1081 *
1082 * Generate the template parameters for the template function
1083 * @param {WebpackCompilation} compilation
1084 * @param {{
1085 publicPath: string,
1086 js: Array<string>,
1087 css: Array<string>,
1088 manifest?: string,
1089 favicon?: string
1090 }} assets
1091 * @param {{
1092 headTags: HtmlTagObject[],
1093 bodyTags: HtmlTagObject[]
1094 }} assetTags
1095 * @param {ProcessedHtmlWebpackOptions} options
1096 * @returns {TemplateParameter}
1097 */
1098function templateParametersGenerator (compilation, assets, assetTags, options) {
1099 return {
1100 compilation: compilation,
1101 webpackConfig: compilation.options,
1102 htmlWebpackPlugin: {
1103 tags: assetTags,
1104 files: assets,
1105 options: options
1106 }
1107 };
1108}
1109
1110// Statics:
1111/**
1112 * The major version number of this plugin
1113 */
1114HtmlWebpackPlugin.version = 5;
1115
1116/**
1117 * A static helper to get the hooks for this plugin
1118 *
1119 * Usage: HtmlWebpackPlugin.getHooks(compilation).HOOK_NAME.tapAsync('YourPluginName', () => { ... });
1120 */
1121HtmlWebpackPlugin.getHooks = getHtmlWebpackPluginHooks;
1122HtmlWebpackPlugin.createHtmlTagObject = createHtmlTagObject;
1123
1124module.exports = HtmlWebpackPlugin;