index.js 44 KB

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