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 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 // To extract the result during the evaluation this part has to be removed.
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 // Evaluate code and cast to string
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 * apply is called by the webpack main compiler during the start phase
151 * @param {import('webpack').Compiler} compiler
152 * @param {ProcessedHtmlWebpackOptions} options
153 * @param {HtmlWebpackPlugin} plugin
154 */
155function hookIntoCompiler (compiler, options, plugin) {
156 const webpack = compiler.webpack;
157 // Instance variables to keep caching information
158 // for multiple builds
159 let assetJson;
160 /**
161 * store the previous generated asset to emit them even if the content did not change
162 * to support watch mode for third party plugins like the clean-webpack-plugin or the compression plugin
163 * @type {Array<{html: string, name: string}>}
164 */
165 let previousEmittedAssets = [];
166
167 options.template = getFullTemplatePath(options.template, compiler.context);
168
169 // Inject child compiler plugin
170 const childCompilerPlugin = new CachedChildCompilation(compiler);
171 if (!options.templateContent) {
172 childCompilerPlugin.addEntry(options.template);
173 }
174
175 // convert absolute filename into relative so that webpack can
176 // generate it at correct location
177 const filename = options.filename;
178 if (path.resolve(filename) === path.normalize(filename)) {
179 const outputPath = /** @type {string} - Once initialized the path is always a string */(compiler.options.output.path);
180 options.filename = path.relative(outputPath, filename);
181 }
182
183 // `contenthash` is introduced in webpack v4.3
184 // which conflicts with the plugin's existing `contenthash` method,
185 // hence it is renamed to `templatehash` to avoid conflicts
186 options.filename = options.filename.replace(/\[(?:(\w+):)?contenthash(?::([a-z]+\d*))?(?::(\d+))?\]/ig, (match) => {
187 return match.replace('contenthash', 'templatehash');
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 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 // If the child compilation was not executed during a previous main compile run
253 // it is a cached result
254 const isCompilationCached = templateResult.mainCompilationHash !== compilation.hash;
255
256 /** The public path used inside the html file */
257 const htmlPublicPath = getPublicPath(compilation, childCompilationOutputName, options.publicPath);
258
259 /** Generated file paths from the entry point names */
260 const assets = htmlWebpackPluginAssets(compilation, sortedEntryNames, htmlPublicPath);
261
262 // If the template and the assets did not change we don't have to emit the html
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 // The html-webpack plugin uses a object representation for the html-tags which will be injected
275 // to allow altering them more easily
276 // Just before they are converted a third-party-plugin author might change the order and content
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 // Turn the js and css paths into grouped HtmlTagObjects
288 const assetTagGroupsPromise = assetsPromise
289 // And allow third-party-plugin authors to reorder and change the assetTags before they are grouped
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 // Inject scripts to body unless it set explicitly to head
306 const scriptTarget = options.inject === 'head' ||
307 (options.inject !== 'body' && options.scriptLoading !== 'blocking') ? 'head' : 'body';
308 // Group assets to `head` and `body` tag arrays
309 const assetGroups = generateAssetGroups(assetTags, scriptTarget);
310 // Allow third-party-plugin authors to reorder and change the assetTags once they are grouped
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 // Turn the compiled template into a nodejs function or into a nodejs string
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 // Allow to use a custom function / string instead
327 if (options.templateContent !== false) {
328 return options.templateContent;
329 }
330 // Once everything is compiled evaluate the html factory
331 // and replace it with its content
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 // Execute the template
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 // Allow plugins to change the html before assets are injected
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 // Allow plugins to change the html after assets are injected
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 // In case anything went wrong the promise is resolved
361 // with the error message and an error is logged
362 compilation.errors.push(prettyError(err, compiler.context).toString());
363 return options.showErrors ? prettyError(err, compiler.context).toHtml() : 'ERROR';
364 })
365 .then(html => {
366 // Allow to use [templatehash] as placeholder for the html-webpack-plugin name
367 // See also https://survivejs.com/webpack/optimizing/adding-hashes-to-filenames/
368 // From https://github.com/webpack-contrib/extract-text-webpack-plugin/blob/8de6558e33487e7606e7cd7cb2adc2cccafef272/src/index.js#L212-L214
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 // Add the evaluated html code to the webpack assets
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 // Once all files are added to the webpack compilation
386 // let the webpack compiler continue
387 emitHtmlPromise.then(() => {
388 callback();
389 });
390 });
391 });
392
393 /**
394 * Generate the template parameters for the template function
395 * @param {WebpackCompilation} compilation
396 * @param {{
397 publicPath: string,
398 js: Array<string>,
399 css: Array<string>,
400 manifest?: string,
401 favicon?: string
402 }} assets
403 * @param {{
404 headTags: HtmlTagObject[],
405 bodyTags: HtmlTagObject[]
406 }} assetTags
407 * @returns {Promise<{[key: any]: any}>}
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 // A custom function can overwrite the entire template parameter preparation
419 ? templateParameters
420 // If the template parameters is an object merge it with the default values
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 * This function renders the actual html by executing the template function
436 *
437 * @param {(templateParameters) => string | Promise<string>} templateFunction
438 * @param {{
439 publicPath: string,
440 js: Array<string>,
441 css: Array<string>,
442 manifest?: string,
443 favicon?: string
444 }} assets
445 * @param {{
446 headTags: HtmlTagObject[],
447 bodyTags: HtmlTagObject[]
448 }} assetTags
449 * @param {WebpackCompilation} compilation
450 *
451 * @returns Promise<string>
452 */
453 function executeTemplate (templateFunction, assets, assetTags, compilation) {
454 // Template processing
455 const templateParamsPromise = getTemplateParameters(compilation, assets, assetTags);
456 return templateParamsPromise.then((templateParams) => {
457 try {
458 // If html is a promise return the promise
459 // If html is a string turn it into a promise
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 * Html Post processing
470 *
471 * @param {any} html
472 * The input html
473 * @param {any} assets
474 * @param {{
475 headTags: HtmlTagObject[],
476 bodyTags: HtmlTagObject[]
477 }} assetTags
478 * The asset tags to inject
479 *
480 * @returns {Promise<string>}
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 * Pushes the content of the given filename to the compilation assets
495 * @param {string} filename
496 * @param {WebpackCompilation} compilation
497 *
498 * @returns {string} file basename
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 * Helper to sort chunks
515 * @param {string[]} entryNames
516 * @param {string|((entryNameA: string, entryNameB: string) => number)} sortMode
517 * @param {WebpackCompilation} compilation
518 */
519 function sortEntryChunks (entryNames, sortMode, compilation) {
520 // Custom function
521 if (typeof sortMode === 'function') {
522 return entryNames.sort(sortMode);
523 }
524 // Check if the given sort mode is a valid chunkSorter sort mode
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 * Return all chunks from the compilation result which match the exclude and include filters
533 * @param {any} chunks
534 * @param {string[]|'all'} includedChunks
535 * @param {string[]} excludedChunks
536 */
537 function filterChunks (chunks, includedChunks, excludedChunks) {
538 return chunks.filter(chunkName => {
539 // Skip if the chunks should be filtered and the given chunk was not added explicity
540 if (Array.isArray(includedChunks) && includedChunks.indexOf(chunkName) === -1) {
541 return false;
542 }
543 // Skip if the chunks should be filtered and the given chunk was excluded explicity
544 if (Array.isArray(excludedChunks) && excludedChunks.indexOf(chunkName) !== -1) {
545 return false;
546 }
547 // Add otherwise
548 return true;
549 });
550 }
551
552 /**
553 * Generate the relative or absolute base url to reference images, css, and javascript files
554 * from within the html file - the publicPath
555 *
556 * @param {WebpackCompilation} compilation
557 * @param {string} childCompilationOutputName
558 * @param {string | 'auto'} customPublicPath
559 * @returns {string}
560 */
561 function getPublicPath (compilation, childCompilationOutputName, customPublicPath) {
562 const compilationHash = compilation.hash;
563
564 /**
565 * @type {string} the configured public path to the asset root
566 * if a path publicPath is set in the current webpack config use it otherwise
567 * fallback to a relative path
568 */
569 const webpackPublicPath = compilation.getAssetPath(compilation.outputOptions.publicPath, { hash: compilationHash });
570
571 // Webpack 5 introduced "auto" as default value
572 const isPublicPathDefined = webpackPublicPath !== 'auto';
573
574 let publicPath =
575 // If the html-webpack-plugin options contain a custom public path uset it
576 customPublicPath !== 'auto'
577 ? customPublicPath
578 : (isPublicPathDefined
579 // If a hard coded public path exists use it
580 ? webpackPublicPath
581 // If no public path was set get a relative url path
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 * The htmlWebpackPluginAssets extracts the asset information of a webpack compilation
595 * for all given entry names
596 * @param {WebpackCompilation} compilation
597 * @param {string[]} entryNames
598 * @param {string | 'auto'} publicPath
599 * @returns {{
600 publicPath: string,
601 js: Array<string>,
602 css: Array<string>,
603 manifest?: string,
604 favicon?: string
605 }}
606 */
607 function htmlWebpackPluginAssets (compilation, entryNames, publicPath) {
608 const compilationHash = compilation.hash;
609 /**
610 * @type {{
611 publicPath: string,
612 js: Array<string>,
613 css: Array<string>,
614 manifest?: string,
615 favicon?: string
616 }}
617 */
618 const assets = {
619 // The public path
620 publicPath,
621 // Will contain all js and mjs files
622 js: [],
623 // Will contain all css files
624 css: [],
625 // Will contain the html5 appcache manifest files if it exists
626 manifest: Object.keys(compilation.assets).find(assetFile => path.extname(assetFile) === '.appcache'),
627 // Favicon
628 favicon: undefined
629 };
630
631 // Append a hash for cache busting
632 if (options.hash && assets.manifest) {
633 assets.manifest = appendHash(assets.manifest, compilationHash);
634 }
635
636 // Extract paths to .js, .mjs and .css files from the current compilation
637 const entryPointPublicPathMap = {};
638 const extensionRegexp = /\.(css|js|mjs)(\?|$)/;
639 for (let i = 0; i < entryNames.length; i++) {
640 const entryName = entryNames[i];
641 /** entryPointUnfilteredFiles - also includes hot module update files */
642 const entryPointUnfilteredFiles = compilation.entrypoints.get(entryName).getFiles();
643
644 const entryPointFiles = entryPointUnfilteredFiles.filter((chunkFile) => {
645 // compilation.getAsset was introduced in webpack 4.4.0
646 // once the support pre webpack 4.4.0 is dropped please
647 // remove the following guard:
648 const asset = compilation.getAsset && compilation.getAsset(chunkFile);
649 if (!asset) {
650 return true;
651 }
652 // Prevent hot-module files from being included:
653 const assetMetaInformation = asset.info || {};
654 return !(assetMetaInformation.hotModuleReplacement || assetMetaInformation.development);
655 });
656
657 // Prepend the publicPath and append the hash depending on the
658 // webpack.output.publicPath and hashOptions
659 // E.g. bundle.js -> /bundle.js?hash
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 // Skip if the public path is not a .css, .mjs or .js file
671 if (!extMatch) {
672 return;
673 }
674 // Skip if this file is already known
675 // (e.g. because of common chunk optimizations)
676 if (entryPointPublicPathMap[entryPointPublicPath]) {
677 return;
678 }
679 entryPointPublicPathMap[entryPointPublicPath] = true;
680 // ext will contain .js or .css, because .mjs recognizes as .js
681 const ext = extMatch[1] === 'mjs' ? 'js' : extMatch[1];
682 assets[ext].push(entryPointPublicPath);
683 });
684 }
685 return assets;
686 }
687
688 /**
689 * Converts a favicon file from disk to a webpack resource
690 * and returns the url to the resource
691 *
692 * @param {string|false} faviconFilePath
693 * @param {WebpackCompilation} compilation
694 * @param {string} publicPath
695 * @returns {Promise<string|undefined>}
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 * Generate all tags script for the given file paths
713 * @param {Array<string>} jsAssets
714 * @returns {Array<HtmlTagObject>}
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 * Generate all style tags for the given file paths
730 * @param {Array<string>} cssAssets
731 * @returns {Array<HtmlTagObject>}
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 * Generate an optional base tag
747 * @param { false
748 | string
749 | {[attributeName: string]: string} // attributes e.g. { href:"http://example.com/page.html" target:"_blank" }
750 } baseOption
751 * @returns {Array<HtmlTagObject>}
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 * Generate all meta tags for the given meta configuration
770 * @param {false | {
771 [name: string]:
772 false // disabled
773 | string // name content pair e.g. {viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no'}`
774 | {[attributeName: string]: string|boolean} // custom properties e.g. { name:"viewport" content:"width=500, initial-scale=1" }
775 }} metaOptions
776 * @returns {Array<HtmlTagObject>}
777 */
778 function generatedMetaTags (metaOptions) {
779 if (metaOptions === false) {
780 return [];
781 }
782 // Make tags self-closing in case of xhtml
783 // Turn { "viewport" : "width=500, initial-scale=1" } into
784 // [{ name:"viewport" content:"width=500, initial-scale=1" }]
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 // Turn [{ name:"viewport" content:"width=500, initial-scale=1" }] into
795 // the html-webpack-plugin tag structure
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 * Generate a favicon tag for the given file path
811 * @param {string| undefined} faviconPath
812 * @returns {Array<HtmlTagObject>}
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 * Group assets to head and bottom tags
831 *
832 * @param {{
833 scripts: Array<HtmlTagObject>;
834 styles: Array<HtmlTagObject>;
835 meta: Array<HtmlTagObject>;
836 }} assetTags
837 * @param {"body" | "head"} scriptTarget
838 * @returns {{
839 headTags: Array<HtmlTagObject>;
840 bodyTags: Array<HtmlTagObject>;
841 }}
842 */
843 function generateAssetGroups (assetTags, scriptTarget) {
844 /** @type {{ headTags: Array<HtmlTagObject>; bodyTags: Array<HtmlTagObject>; }} */
845 const result = {
846 headTags: [
847 ...assetTags.meta,
848 ...assetTags.styles
849 ],
850 bodyTags: []
851 };
852 // Add script tags to head or body depending on
853 // the htmlPluginOptions
854 if (scriptTarget === 'body') {
855 result.bodyTags.push(...assetTags.scripts);
856 } else {
857 // If script loading is blocking add the scripts to the end of the head
858 // If script loading is non-blocking add the scripts infront of the css files
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 * Add toString methods for easier rendering
867 * inside the template
868 *
869 * @param {Array<HtmlTagObject>} assetTagGroup
870 * @returns {Array<HtmlTagObject>}
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 * Injects the assets into the given html string
885 *
886 * @param {string} html
887 * The input html
888 * @param {any} assets
889 * @param {{
890 headTags: HtmlTagObject[],
891 bodyTags: HtmlTagObject[]
892 }} assetTags
893 * The asset tags to inject
894 *
895 * @returns {string}
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 // Append assets to body element
907 html = html.replace(bodyRegExp, match => body.join('') + match);
908 } else {
909 // Append scripts to the end of the file if no <body> element exists:
910 html += body.join('');
911 }
912 }
913
914 if (head.length) {
915 // Create a head tag if none exists
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 // Append assets to head element
925 html = html.replace(headRegExp, match => head.join('') + match);
926 }
927
928 // Inject manifest into the opening html tag
929 if (assets.manifest) {
930 html = html.replace(/(<html[^>]*)(>)/i, (match, start, end) => {
931 // Append the manifest only if no manifest was specified
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 * Appends a cache busting hash to the query string of the url
943 * E.g. http://localhost:8080/ -> http://localhost:8080/?50c9096ba6183fd728eeb065a26ec175
944 * @param {string} url
945 * @param {string} hash
946 */
947 function appendHash (url, hash) {
948 if (!url) {
949 return url;
950 }
951 return url + (url.indexOf('?') === -1 ? '?' : '&') + hash;
952 }
953
954 /**
955 * Encode each path component using `encodeURIComponent` as files can contain characters
956 * which needs special encoding in URLs like `+ `.
957 *
958 * Valid filesystem characters which need to be encoded for urls:
959 *
960 * # pound, % percent, & ampersand, { left curly bracket, } right curly bracket,
961 * \ back slash, < left angle bracket, > right angle bracket, * asterisk, ? question mark,
962 * blank spaces, $ dollar sign, ! exclamation point, ' single quotes, " double quotes,
963 * : colon, @ at sign, + plus sign, ` backtick, | pipe, = equal sign
964 *
965 * However the query string must not be encoded:
966 *
967 * fo:demonstration-path/very fancy+name.js?path=/home?value=abc&value=def#zzz
968 * ^ ^ ^ ^ ^ ^ ^ ^^ ^ ^ ^ ^ ^
969 * | | | | | | | || | | | | |
970 * encoded | | encoded | | || | | | | |
971 * ignored ignored ignored ignored ignored
972 *
973 * @param {string} filePath
974 */
975 function urlencodePath (filePath) {
976 // People use the filepath in quite unexpected ways.
977 // Try to extract the first querystring of the url:
978 //
979 // some+path/demo.html?value=abc?def
980 //
981 const queryStringStart = filePath.indexOf('?');
982 const urlPath = queryStringStart === -1 ? filePath : filePath.substr(0, queryStringStart);
983 const queryString = filePath.substr(urlPath.length);
984 // Encode all parts except '/' which are not part of the querystring:
985 const encodedUrlPath = urlPath.split('/').map(encodeURIComponent).join('/');
986 return encodedUrlPath + queryString;
987 }
988
989 /**
990 * Helper to return the absolute template path with a fallback loader
991 * @param {string} template
992 * The path to the template e.g. './index.html'
993 * @param {string} context
994 * The webpack base resolution path for relative paths e.g. process.cwd()
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 // If the template doesn't use a loader use the lodash template loader
1004 if (template.indexOf('!') === -1) {
1005 template = require.resolve('./lib/loader.js') + '!' + path.resolve(context, template);
1006 }
1007 // Resolve template path
1008 return template.replace(
1009 /([!])([^/\\][^!?]+|[^/\\!?])($|\?[^!?\n]+$)/,
1010 (match, prefix, filepath, postfix) => prefix + path.resolve(filepath) + postfix);
1011 }
1012
1013 /**
1014 * Minify the given string using html-minifier-terser
1015 *
1016 * As this is a breaking change to html-webpack-plugin 3.x
1017 * provide an extended error message to explain how to get back
1018 * to the old behaviour
1019 *
1020 * @param {string} html
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 * Helper to return a sorted unique array of all asset files out of the
1047 * asset object
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 * The default for options.templateParameter
1058 * Generate the template parameters
1059 *
1060 * Generate the template parameters for the template function
1061 * @param {WebpackCompilation} compilation
1062 * @param {{
1063 publicPath: string,
1064 js: Array<string>,
1065 css: Array<string>,
1066 manifest?: string,
1067 favicon?: string
1068 }} assets
1069 * @param {{
1070 headTags: HtmlTagObject[],
1071 bodyTags: HtmlTagObject[]
1072 }} assetTags
1073 * @param {ProcessedHtmlWebpackOptions} options
1074 * @returns {TemplateParameter}
1075 */
1076function 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// Statics:
1089/**
1090 * The major version number of this plugin
1091 */
1092HtmlWebpackPlugin.version = 5;
1093
1094/**
1095 * A static helper to get the hooks for this plugin
1096 *
1097 * Usage: HtmlWebpackPlugin.getHooks(compilation).HOOK_NAME.tapAsync('YourPluginName', () => { ... });
1098 */
1099HtmlWebpackPlugin.getHooks = getHtmlWebpackPluginHooks;
1100HtmlWebpackPlugin.createHtmlTagObject = createHtmlTagObject;
1101
1102module.exports = HtmlWebpackPlugin;