UNPKG

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