index.js 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  1. // @ts-check
  2. "use strict";
  3. const promisify = require("util").promisify;
  4. const vm = require("vm");
  5. const fs = require("fs");
  6. const _uniq = require("lodash/uniq");
  7. const path = require("path");
  8. const { CachedChildCompilation } = require("./lib/cached-child-compiler");
  9. const {
  10. createHtmlTagObject,
  11. htmlTagObjectToString,
  12. HtmlTagArray,
  13. } = require("./lib/html-tags");
  14. const prettyError = require("./lib/errors.js");
  15. const chunkSorter = require("./lib/chunksorter.js");
  16. const { AsyncSeriesWaterfallHook } = require("tapable");
  17. /** @typedef {import("./typings").HtmlTagObject} HtmlTagObject */
  18. /** @typedef {import("./typings").Options} HtmlWebpackOptions */
  19. /** @typedef {import("./typings").ProcessedOptions} ProcessedHtmlWebpackOptions */
  20. /** @typedef {import("./typings").TemplateParameter} TemplateParameter */
  21. /** @typedef {import("webpack").Compiler} Compiler */
  22. /** @typedef {import("webpack").Compilation} Compilation */
  23. /** @typedef {Required<Compilation["outputOptions"]["publicPath"]>} PublicPath */
  24. /** @typedef {ReturnType<Compiler["getInfrastructureLogger"]>} Logger */
  25. /** @typedef {Compilation["entrypoints"] extends Map<string, infer I> ? I : never} Entrypoint */
  26. /** @typedef {Array<{ name: string, source: import('webpack').sources.Source, info?: import('webpack').AssetInfo }>} PreviousEmittedAssets */
  27. /** @typedef {{ publicPath: string, js: Array<string>, css: Array<string>, manifest?: string, favicon?: string }} AssetsInformationByGroups */
  28. /** @typedef {import("./typings").Hooks} HtmlWebpackPluginHooks */
  29. /**
  30. * @type {WeakMap<Compilation, HtmlWebpackPluginHooks>}}
  31. */
  32. const compilationHooksMap = new WeakMap();
  33. class HtmlWebpackPlugin {
  34. // The following is the API definition for all available hooks
  35. // For the TypeScript definition, see the Hooks type in typings.d.ts
  36. /**
  37. beforeAssetTagGeneration:
  38. AsyncSeriesWaterfallHook<{
  39. assets: {
  40. publicPath: string,
  41. js: Array<string>,
  42. css: Array<string>,
  43. favicon?: string | undefined,
  44. manifest?: string | undefined
  45. },
  46. outputName: string,
  47. plugin: HtmlWebpackPlugin
  48. }>,
  49. alterAssetTags:
  50. AsyncSeriesWaterfallHook<{
  51. assetTags: {
  52. scripts: Array<HtmlTagObject>,
  53. styles: Array<HtmlTagObject>,
  54. meta: Array<HtmlTagObject>,
  55. },
  56. publicPath: string,
  57. outputName: string,
  58. plugin: HtmlWebpackPlugin
  59. }>,
  60. alterAssetTagGroups:
  61. AsyncSeriesWaterfallHook<{
  62. headTags: Array<HtmlTagObject | HtmlTagObject>,
  63. bodyTags: Array<HtmlTagObject | HtmlTagObject>,
  64. publicPath: string,
  65. outputName: string,
  66. plugin: HtmlWebpackPlugin
  67. }>,
  68. afterTemplateExecution:
  69. AsyncSeriesWaterfallHook<{
  70. html: string,
  71. headTags: Array<HtmlTagObject | HtmlTagObject>,
  72. bodyTags: Array<HtmlTagObject | HtmlTagObject>,
  73. outputName: string,
  74. plugin: HtmlWebpackPlugin,
  75. }>,
  76. beforeEmit:
  77. AsyncSeriesWaterfallHook<{
  78. html: string,
  79. outputName: string,
  80. plugin: HtmlWebpackPlugin,
  81. }>,
  82. afterEmit:
  83. AsyncSeriesWaterfallHook<{
  84. outputName: string,
  85. plugin: HtmlWebpackPlugin
  86. }>
  87. */
  88. /**
  89. * Returns all public hooks of the html webpack plugin for the given compilation
  90. *
  91. * @param {Compilation} compilation
  92. * @returns {HtmlWebpackPluginHooks}
  93. */
  94. static getCompilationHooks(compilation) {
  95. let hooks = compilationHooksMap.get(compilation);
  96. if (!hooks) {
  97. hooks = {
  98. beforeAssetTagGeneration: new AsyncSeriesWaterfallHook(["pluginArgs"]),
  99. alterAssetTags: new AsyncSeriesWaterfallHook(["pluginArgs"]),
  100. alterAssetTagGroups: new AsyncSeriesWaterfallHook(["pluginArgs"]),
  101. afterTemplateExecution: new AsyncSeriesWaterfallHook(["pluginArgs"]),
  102. beforeEmit: new AsyncSeriesWaterfallHook(["pluginArgs"]),
  103. afterEmit: new AsyncSeriesWaterfallHook(["pluginArgs"]),
  104. };
  105. compilationHooksMap.set(compilation, hooks);
  106. }
  107. return hooks;
  108. }
  109. /**
  110. * @param {HtmlWebpackOptions} [options]
  111. */
  112. constructor(options) {
  113. /** @type {HtmlWebpackOptions} */
  114. // TODO remove me in the next major release
  115. this.userOptions = options || {};
  116. this.version = HtmlWebpackPlugin.version;
  117. // Default options
  118. /** @type {ProcessedHtmlWebpackOptions} */
  119. const defaultOptions = {
  120. template: "auto",
  121. templateContent: false,
  122. templateParameters: templateParametersGenerator,
  123. filename: "index.html",
  124. publicPath:
  125. this.userOptions.publicPath === undefined
  126. ? "auto"
  127. : this.userOptions.publicPath,
  128. hash: false,
  129. inject: this.userOptions.scriptLoading === "blocking" ? "body" : "head",
  130. scriptLoading: "defer",
  131. compile: true,
  132. favicon: false,
  133. minify: "auto",
  134. cache: true,
  135. showErrors: true,
  136. chunks: "all",
  137. excludeChunks: [],
  138. chunksSortMode: "auto",
  139. meta: {},
  140. base: false,
  141. title: "Webpack App",
  142. xhtml: false,
  143. };
  144. /** @type {ProcessedHtmlWebpackOptions} */
  145. this.options = Object.assign(defaultOptions, this.userOptions);
  146. }
  147. /**
  148. *
  149. * @param {Compiler} compiler
  150. * @returns {void}
  151. */
  152. apply(compiler) {
  153. this.logger = compiler.getInfrastructureLogger("HtmlWebpackPlugin");
  154. const options = this.options;
  155. options.template = this.getTemplatePath(
  156. this.options.template,
  157. compiler.context,
  158. );
  159. // Assert correct option spelling
  160. if (
  161. options.scriptLoading !== "defer" &&
  162. options.scriptLoading !== "blocking" &&
  163. options.scriptLoading !== "module" &&
  164. options.scriptLoading !== "systemjs-module"
  165. ) {
  166. /** @type {Logger} */
  167. (this.logger).error(
  168. 'The "scriptLoading" option need to be set to "defer", "blocking" or "module" or "systemjs-module"',
  169. );
  170. }
  171. if (
  172. options.inject !== true &&
  173. options.inject !== false &&
  174. options.inject !== "head" &&
  175. options.inject !== "body"
  176. ) {
  177. /** @type {Logger} */
  178. (this.logger).error(
  179. 'The `inject` option needs to be set to true, false, "head" or "body',
  180. );
  181. }
  182. if (
  183. this.options.templateParameters !== false &&
  184. typeof this.options.templateParameters !== "function" &&
  185. typeof this.options.templateParameters !== "object"
  186. ) {
  187. /** @type {Logger} */
  188. (this.logger).error(
  189. "The `templateParameters` has to be either a function or an object or false",
  190. );
  191. }
  192. // Default metaOptions if no template is provided
  193. if (
  194. !this.userOptions.template &&
  195. options.templateContent === false &&
  196. options.meta
  197. ) {
  198. options.meta = Object.assign(
  199. {},
  200. options.meta,
  201. {
  202. // TODO remove in the next major release
  203. // From https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag
  204. viewport: "width=device-width, initial-scale=1",
  205. },
  206. this.userOptions.meta,
  207. );
  208. }
  209. // entryName to fileName conversion function
  210. const userOptionFilename =
  211. this.userOptions.filename || this.options.filename;
  212. const filenameFunction =
  213. typeof userOptionFilename === "function"
  214. ? userOptionFilename
  215. : // Replace '[name]' with entry name
  216. (entryName) => userOptionFilename.replace(/\[name\]/g, entryName);
  217. /** output filenames for the given entry names */
  218. const entryNames = Object.keys(compiler.options.entry);
  219. const outputFileNames = new Set(
  220. (entryNames.length ? entryNames : ["main"]).map(filenameFunction),
  221. );
  222. // Hook all options into the webpack compiler
  223. outputFileNames.forEach((outputFileName) => {
  224. // Instance variables to keep caching information for multiple builds
  225. const assetJson = { value: undefined };
  226. /**
  227. * store the previous generated asset to emit them even if the content did not change
  228. * to support watch mode for third party plugins like the clean-webpack-plugin or the compression plugin
  229. * @type {PreviousEmittedAssets}
  230. */
  231. const previousEmittedAssets = [];
  232. // Inject child compiler plugin
  233. const childCompilerPlugin = new CachedChildCompilation(compiler);
  234. if (!this.options.templateContent) {
  235. childCompilerPlugin.addEntry(this.options.template);
  236. }
  237. // convert absolute filename into relative so that webpack can
  238. // generate it at correct location
  239. let filename = outputFileName;
  240. if (path.resolve(filename) === path.normalize(filename)) {
  241. const outputPath =
  242. /** @type {string} - Once initialized the path is always a string */ (
  243. compiler.options.output.path
  244. );
  245. filename = path.relative(outputPath, filename);
  246. }
  247. compiler.hooks.thisCompilation.tap(
  248. "HtmlWebpackPlugin",
  249. /**
  250. * Hook into the webpack compilation
  251. * @param {Compilation} compilation
  252. */
  253. (compilation) => {
  254. compilation.hooks.processAssets.tapAsync(
  255. {
  256. name: "HtmlWebpackPlugin",
  257. stage:
  258. /**
  259. * Generate the html after minification and dev tooling is done
  260. */
  261. compiler.webpack.Compilation
  262. .PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE,
  263. },
  264. /**
  265. * Hook into the process assets hook
  266. * @param {any} _
  267. * @param {(err?: Error) => void} callback
  268. */
  269. (_, callback) => {
  270. this.generateHTML(
  271. compiler,
  272. compilation,
  273. filename,
  274. childCompilerPlugin,
  275. previousEmittedAssets,
  276. assetJson,
  277. callback,
  278. );
  279. },
  280. );
  281. },
  282. );
  283. });
  284. }
  285. /**
  286. * Helper to return the absolute template path with a fallback loader
  287. *
  288. * @private
  289. * @param {string} template The path to the template e.g. './index.html'
  290. * @param {string} context The webpack base resolution path for relative paths e.g. process.cwd()
  291. */
  292. getTemplatePath(template, context) {
  293. if (template === "auto") {
  294. template = path.resolve(context, "src/index.ejs");
  295. if (!fs.existsSync(template)) {
  296. template = path.join(__dirname, "default_index.ejs");
  297. }
  298. }
  299. // If the template doesn't use a loader use the lodash template loader
  300. if (template.indexOf("!") === -1) {
  301. template =
  302. require.resolve("./lib/loader.js") +
  303. "!" +
  304. path.resolve(context, template);
  305. }
  306. // Resolve template path
  307. return template.replace(
  308. /([!])([^/\\][^!?]+|[^/\\!?])($|\?[^!?\n]+$)/,
  309. (match, prefix, filepath, postfix) =>
  310. prefix + path.resolve(filepath) + postfix,
  311. );
  312. }
  313. /**
  314. * Return all chunks from the compilation result which match the exclude and include filters
  315. *
  316. * @private
  317. * @param {any} chunks
  318. * @param {string[]|'all'} includedChunks
  319. * @param {string[]} excludedChunks
  320. */
  321. filterEntryChunks(chunks, includedChunks, excludedChunks) {
  322. return chunks.filter((chunkName) => {
  323. // Skip if the chunks should be filtered and the given chunk was not added explicity
  324. if (
  325. Array.isArray(includedChunks) &&
  326. includedChunks.indexOf(chunkName) === -1
  327. ) {
  328. return false;
  329. }
  330. // Skip if the chunks should be filtered and the given chunk was excluded explicity
  331. if (
  332. Array.isArray(excludedChunks) &&
  333. excludedChunks.indexOf(chunkName) !== -1
  334. ) {
  335. return false;
  336. }
  337. // Add otherwise
  338. return true;
  339. });
  340. }
  341. /**
  342. * Helper to sort chunks
  343. *
  344. * @private
  345. * @param {string[]} entryNames
  346. * @param {string|((entryNameA: string, entryNameB: string) => number)} sortMode
  347. * @param {Compilation} compilation
  348. */
  349. sortEntryChunks(entryNames, sortMode, compilation) {
  350. // Custom function
  351. if (typeof sortMode === "function") {
  352. return entryNames.sort(sortMode);
  353. }
  354. // Check if the given sort mode is a valid chunkSorter sort mode
  355. if (typeof chunkSorter[sortMode] !== "undefined") {
  356. return chunkSorter[sortMode](entryNames, compilation, this.options);
  357. }
  358. throw new Error('"' + sortMode + '" is not a valid chunk sort mode');
  359. }
  360. /**
  361. * Encode each path component using `encodeURIComponent` as files can contain characters
  362. * which needs special encoding in URLs like `+ `.
  363. *
  364. * Valid filesystem characters which need to be encoded for urls:
  365. *
  366. * # pound, % percent, & ampersand, { left curly bracket, } right curly bracket,
  367. * \ back slash, < left angle bracket, > right angle bracket, * asterisk, ? question mark,
  368. * blank spaces, $ dollar sign, ! exclamation point, ' single quotes, " double quotes,
  369. * : colon, @ at sign, + plus sign, ` backtick, | pipe, = equal sign
  370. *
  371. * However the query string must not be encoded:
  372. *
  373. * fo:demonstration-path/very fancy+name.js?path=/home?value=abc&value=def#zzz
  374. * ^ ^ ^ ^ ^ ^ ^ ^^ ^ ^ ^ ^ ^
  375. * | | | | | | | || | | | | |
  376. * encoded | | encoded | | || | | | | |
  377. * ignored ignored ignored ignored ignored
  378. *
  379. * @private
  380. * @param {string} filePath
  381. */
  382. urlencodePath(filePath) {
  383. // People use the filepath in quite unexpected ways.
  384. // Try to extract the first querystring of the url:
  385. //
  386. // some+path/demo.html?value=abc?def
  387. //
  388. const queryStringStart = filePath.indexOf("?");
  389. const urlPath =
  390. queryStringStart === -1 ? filePath : filePath.substr(0, queryStringStart);
  391. const queryString = filePath.substr(urlPath.length);
  392. // Encode all parts except '/' which are not part of the querystring:
  393. const encodedUrlPath = urlPath.split("/").map(encodeURIComponent).join("/");
  394. return encodedUrlPath + queryString;
  395. }
  396. /**
  397. * Appends a cache busting hash to the query string of the url
  398. * E.g. http://localhost:8080/ -> http://localhost:8080/?50c9096ba6183fd728eeb065a26ec175
  399. *
  400. * @private
  401. * @param {string | undefined} url
  402. * @param {string} hash
  403. */
  404. appendHash(url, hash) {
  405. if (!url) {
  406. return url;
  407. }
  408. return url + (url.indexOf("?") === -1 ? "?" : "&") + hash;
  409. }
  410. /**
  411. * Generate the relative or absolute base url to reference images, css, and javascript files
  412. * from within the html file - the publicPath
  413. *
  414. * @private
  415. * @param {Compilation} compilation
  416. * @param {string} filename
  417. * @param {string | 'auto'} customPublicPath
  418. * @returns {string}
  419. */
  420. getPublicPath(compilation, filename, customPublicPath) {
  421. /**
  422. * @type {string} the configured public path to the asset root
  423. * if a path publicPath is set in the current webpack config use it otherwise
  424. * fallback to a relative path
  425. */
  426. const webpackPublicPath = compilation.getAssetPath(
  427. /** @type {NonNullable<Compilation["outputOptions"]["publicPath"]>} */ (
  428. compilation.outputOptions.publicPath
  429. ),
  430. { hash: compilation.hash },
  431. );
  432. // Webpack 5 introduced "auto" as default value
  433. const isPublicPathDefined = webpackPublicPath !== "auto";
  434. let publicPath =
  435. // If the html-webpack-plugin options contain a custom public path unset it
  436. customPublicPath !== "auto"
  437. ? customPublicPath
  438. : isPublicPathDefined
  439. ? // If a hard coded public path exists use it
  440. webpackPublicPath
  441. : // If no public path was set get a relative url path
  442. path
  443. .relative(
  444. path.resolve(
  445. /** @type {string} */ (compilation.options.output.path),
  446. path.dirname(filename),
  447. ),
  448. /** @type {string} */ (compilation.options.output.path),
  449. )
  450. .split(path.sep)
  451. .join("/");
  452. if (publicPath.length && publicPath.substr(-1, 1) !== "/") {
  453. publicPath += "/";
  454. }
  455. return publicPath;
  456. }
  457. /**
  458. * The getAssetsForHTML extracts the asset information of a webpack compilation for all given entry names.
  459. *
  460. * @private
  461. * @param {Compilation} compilation
  462. * @param {string} outputName
  463. * @param {string[]} entryNames
  464. * @returns {AssetsInformationByGroups}
  465. */
  466. getAssetsInformationByGroups(compilation, outputName, entryNames) {
  467. /** The public path used inside the html file */
  468. const publicPath = this.getPublicPath(
  469. compilation,
  470. outputName,
  471. this.options.publicPath,
  472. );
  473. /**
  474. * @type {AssetsInformationByGroups}
  475. */
  476. const assets = {
  477. // The public path
  478. publicPath,
  479. // Will contain all js and mjs files
  480. js: [],
  481. // Will contain all css files
  482. css: [],
  483. // Will contain the html5 appcache manifest files if it exists
  484. manifest: Object.keys(compilation.assets).find(
  485. (assetFile) => path.extname(assetFile) === ".appcache",
  486. ),
  487. // Favicon
  488. favicon: undefined,
  489. };
  490. // Append a hash for cache busting
  491. if (this.options.hash && assets.manifest) {
  492. assets.manifest = this.appendHash(
  493. assets.manifest,
  494. /** @type {string} */ (compilation.hash),
  495. );
  496. }
  497. // Extract paths to .js, .mjs and .css files from the current compilation
  498. const entryPointPublicPathMap = {};
  499. const extensionRegexp = /\.(css|js|mjs)(\?|$)/;
  500. for (let i = 0; i < entryNames.length; i++) {
  501. const entryName = entryNames[i];
  502. /** entryPointUnfilteredFiles - also includes hot module update files */
  503. const entryPointUnfilteredFiles = /** @type {Entrypoint} */ (
  504. compilation.entrypoints.get(entryName)
  505. ).getFiles();
  506. const entryPointFiles = entryPointUnfilteredFiles.filter((chunkFile) => {
  507. const asset = compilation.getAsset(chunkFile);
  508. if (!asset) {
  509. return true;
  510. }
  511. // Prevent hot-module files from being included:
  512. const assetMetaInformation = asset.info || {};
  513. return !(
  514. assetMetaInformation.hotModuleReplacement ||
  515. assetMetaInformation.development
  516. );
  517. });
  518. // Prepend the publicPath and append the hash depending on the
  519. // webpack.output.publicPath and hashOptions
  520. // E.g. bundle.js -> /bundle.js?hash
  521. const entryPointPublicPaths = entryPointFiles.map((chunkFile) => {
  522. const entryPointPublicPath = publicPath + this.urlencodePath(chunkFile);
  523. return this.options.hash
  524. ? this.appendHash(
  525. entryPointPublicPath,
  526. /** @type {string} */ (compilation.hash),
  527. )
  528. : entryPointPublicPath;
  529. });
  530. entryPointPublicPaths.forEach((entryPointPublicPath) => {
  531. const extMatch = extensionRegexp.exec(
  532. /** @type {string} */ (entryPointPublicPath),
  533. );
  534. // Skip if the public path is not a .css, .mjs or .js file
  535. if (!extMatch) {
  536. return;
  537. }
  538. // Skip if this file is already known
  539. // (e.g. because of common chunk optimizations)
  540. if (entryPointPublicPathMap[entryPointPublicPath]) {
  541. return;
  542. }
  543. entryPointPublicPathMap[entryPointPublicPath] = true;
  544. // ext will contain .js or .css, because .mjs recognizes as .js
  545. const ext = extMatch[1] === "mjs" ? "js" : extMatch[1];
  546. assets[ext].push(entryPointPublicPath);
  547. });
  548. }
  549. return assets;
  550. }
  551. /**
  552. * Once webpack is done with compiling the template into a NodeJS code this function
  553. * evaluates it to generate the html result
  554. *
  555. * The evaluateCompilationResult is only a class function to allow spying during testing.
  556. * Please change that in a further refactoring
  557. *
  558. * @param {string} source
  559. * @param {string} publicPath
  560. * @param {string} templateFilename
  561. * @returns {Promise<string | (() => string | Promise<string>)>}
  562. */
  563. evaluateCompilationResult(source, publicPath, templateFilename) {
  564. if (!source) {
  565. return Promise.reject(
  566. new Error("The child compilation didn't provide a result"),
  567. );
  568. }
  569. // The LibraryTemplatePlugin stores the template result in a local variable.
  570. // By adding it to the end the value gets extracted during evaluation
  571. if (source.indexOf("HTML_WEBPACK_PLUGIN_RESULT") >= 0) {
  572. source += ";\nHTML_WEBPACK_PLUGIN_RESULT";
  573. }
  574. const templateWithoutLoaders = templateFilename
  575. .replace(/^.+!/, "")
  576. .replace(/\?.+$/, "");
  577. const globalClone = Object.create(
  578. Object.getPrototypeOf(global),
  579. Object.getOwnPropertyDescriptors(global),
  580. );
  581. // Presence of `eval` and `Function` breaks template's explicit `eval` call
  582. // Ref: https://github.com/nodejs/help/issues/2880
  583. delete globalClone.eval;
  584. delete globalClone.Function;
  585. // Not using `...global` as it throws when localStorage is not explicitly enabled in Node 25+
  586. const vmContext = vm.createContext(
  587. Object.assign(globalClone, {
  588. HTML_WEBPACK_PLUGIN: true,
  589. // Copying nonstandard globals like `require` explicitly as they may be absent from `global`
  590. require: require,
  591. htmlWebpackPluginPublicPath: publicPath,
  592. __filename: templateWithoutLoaders,
  593. __dirname: path.dirname(templateWithoutLoaders),
  594. }),
  595. );
  596. const vmScript = new vm.Script(source, {
  597. filename: templateWithoutLoaders,
  598. });
  599. // Evaluate code and cast to string
  600. let newSource;
  601. try {
  602. newSource = vmScript.runInContext(vmContext);
  603. } catch (e) {
  604. return Promise.reject(e);
  605. }
  606. if (
  607. typeof newSource === "object" &&
  608. newSource.__esModule &&
  609. newSource.default !== undefined
  610. ) {
  611. newSource = newSource.default;
  612. }
  613. return typeof newSource === "string" || typeof newSource === "function"
  614. ? Promise.resolve(newSource)
  615. : Promise.reject(
  616. new Error(
  617. 'The loader "' + templateWithoutLoaders + "\" didn't return html.",
  618. ),
  619. );
  620. }
  621. /**
  622. * Add toString methods for easier rendering inside the template
  623. *
  624. * @private
  625. * @param {Array<HtmlTagObject>} assetTagGroup
  626. * @returns {Array<HtmlTagObject>}
  627. */
  628. prepareAssetTagGroupForRendering(assetTagGroup) {
  629. const xhtml = this.options.xhtml;
  630. return HtmlTagArray.from(
  631. assetTagGroup.map((assetTag) => {
  632. const copiedAssetTag = Object.assign({}, assetTag);
  633. copiedAssetTag.toString = function () {
  634. return htmlTagObjectToString(this, xhtml);
  635. };
  636. return copiedAssetTag;
  637. }),
  638. );
  639. }
  640. /**
  641. * Generate the template parameters for the template function
  642. *
  643. * @private
  644. * @param {Compilation} compilation
  645. * @param {AssetsInformationByGroups} assetsInformationByGroups
  646. * @param {{
  647. headTags: HtmlTagObject[],
  648. bodyTags: HtmlTagObject[]
  649. }} assetTags
  650. * @returns {Promise<{[key: any]: any}>}
  651. */
  652. getTemplateParameters(compilation, assetsInformationByGroups, assetTags) {
  653. const templateParameters = this.options.templateParameters;
  654. if (templateParameters === false) {
  655. return Promise.resolve({});
  656. }
  657. if (
  658. typeof templateParameters !== "function" &&
  659. typeof templateParameters !== "object"
  660. ) {
  661. throw new Error(
  662. "templateParameters has to be either a function or an object",
  663. );
  664. }
  665. const templateParameterFunction =
  666. typeof templateParameters === "function"
  667. ? // A custom function can overwrite the entire template parameter preparation
  668. templateParameters
  669. : // If the template parameters is an object merge it with the default values
  670. (compilation, assetsInformationByGroups, assetTags, options) =>
  671. Object.assign(
  672. {},
  673. templateParametersGenerator(
  674. compilation,
  675. assetsInformationByGroups,
  676. assetTags,
  677. options,
  678. ),
  679. templateParameters,
  680. );
  681. const preparedAssetTags = {
  682. headTags: this.prepareAssetTagGroupForRendering(assetTags.headTags),
  683. bodyTags: this.prepareAssetTagGroupForRendering(assetTags.bodyTags),
  684. };
  685. return Promise.resolve().then(() =>
  686. templateParameterFunction(
  687. compilation,
  688. assetsInformationByGroups,
  689. preparedAssetTags,
  690. this.options,
  691. ),
  692. );
  693. }
  694. /**
  695. * This function renders the actual html by executing the template function
  696. *
  697. * @private
  698. * @param {(templateParameters) => string | Promise<string>} templateFunction
  699. * @param {AssetsInformationByGroups} assetsInformationByGroups
  700. * @param {{
  701. headTags: HtmlTagObject[],
  702. bodyTags: HtmlTagObject[]
  703. }} assetTags
  704. * @param {Compilation} compilation
  705. * @returns Promise<string>
  706. */
  707. executeTemplate(
  708. templateFunction,
  709. assetsInformationByGroups,
  710. assetTags,
  711. compilation,
  712. ) {
  713. // Template processing
  714. const templateParamsPromise = this.getTemplateParameters(
  715. compilation,
  716. assetsInformationByGroups,
  717. assetTags,
  718. );
  719. return templateParamsPromise.then((templateParams) => {
  720. try {
  721. // If html is a promise return the promise
  722. // If html is a string turn it into a promise
  723. return templateFunction(templateParams);
  724. } catch (e) {
  725. // @ts-ignore
  726. compilation.errors.push(new Error("Template execution failed: " + e));
  727. return Promise.reject(e);
  728. }
  729. });
  730. }
  731. /**
  732. * Html Post processing
  733. *
  734. * @private
  735. * @param {Compiler} compiler The compiler instance
  736. * @param {any} originalHtml The input html
  737. * @param {AssetsInformationByGroups} assetsInformationByGroups
  738. * @param {{headTags: HtmlTagObject[], bodyTags: HtmlTagObject[]}} assetTags The asset tags to inject
  739. * @returns {Promise<string>}
  740. */
  741. postProcessHtml(
  742. compiler,
  743. originalHtml,
  744. assetsInformationByGroups,
  745. assetTags,
  746. ) {
  747. let html = originalHtml;
  748. if (typeof html !== "string") {
  749. return Promise.reject(
  750. new Error(
  751. "Expected html to be a string but got " + JSON.stringify(html),
  752. ),
  753. );
  754. }
  755. if (this.options.inject) {
  756. const htmlRegExp = /(<html[^>]*>)/i;
  757. const headRegExp = /(<\/head\s*>)/i;
  758. const bodyRegExp = /(<\/body\s*>)/i;
  759. const metaViewportRegExp = /<meta[^>]+name=["']viewport["'][^>]*>/i;
  760. const body = assetTags.bodyTags.map((assetTagObject) =>
  761. htmlTagObjectToString(assetTagObject, this.options.xhtml),
  762. );
  763. const head = assetTags.headTags
  764. .filter((item) => {
  765. if (
  766. item.tagName === "meta" &&
  767. item.attributes &&
  768. item.attributes.name === "viewport" &&
  769. metaViewportRegExp.test(html)
  770. ) {
  771. return false;
  772. }
  773. return true;
  774. })
  775. .map((assetTagObject) =>
  776. htmlTagObjectToString(assetTagObject, this.options.xhtml),
  777. );
  778. if (body.length) {
  779. if (bodyRegExp.test(html)) {
  780. // Append assets to body element
  781. html = html.replace(bodyRegExp, (match) => body.join("") + match);
  782. } else {
  783. // Append scripts to the end of the file if no <body> element exists:
  784. html += body.join("");
  785. }
  786. }
  787. if (head.length) {
  788. // Create a head tag if none exists
  789. if (!headRegExp.test(html)) {
  790. if (!htmlRegExp.test(html)) {
  791. html = "<head></head>" + html;
  792. } else {
  793. html = html.replace(htmlRegExp, (match) => match + "<head></head>");
  794. }
  795. }
  796. // Append assets to head element
  797. html = html.replace(headRegExp, (match) => head.join("") + match);
  798. }
  799. // Inject manifest into the opening html tag
  800. if (assetsInformationByGroups.manifest) {
  801. html = html.replace(/(<html[^>]*)(>)/i, (match, start, end) => {
  802. // Append the manifest only if no manifest was specified
  803. if (/\smanifest\s*=/.test(match)) {
  804. return match;
  805. }
  806. return (
  807. start +
  808. ' manifest="' +
  809. assetsInformationByGroups.manifest +
  810. '"' +
  811. end
  812. );
  813. });
  814. }
  815. }
  816. // TODO avoid this logic and use https://github.com/webpack-contrib/html-minimizer-webpack-plugin under the hood in the next major version
  817. // Check if webpack is running in production mode
  818. // @see https://github.com/webpack/webpack/blob/3366421f1784c449f415cda5930a8e445086f688/lib/WebpackOptionsDefaulter.js#L12-L14
  819. const isProductionLikeMode =
  820. compiler.options.mode === "production" || !compiler.options.mode;
  821. const needMinify =
  822. this.options.minify === true ||
  823. typeof this.options.minify === "object" ||
  824. (this.options.minify === "auto" && isProductionLikeMode);
  825. if (!needMinify) {
  826. return Promise.resolve(html);
  827. }
  828. const minifyOptions =
  829. typeof this.options.minify === "object"
  830. ? this.options.minify
  831. : {
  832. // https://www.npmjs.com/package/html-minifier-terser#options-quick-reference
  833. collapseWhitespace: true,
  834. keepClosingSlash: true,
  835. removeComments: true,
  836. removeRedundantAttributes: true,
  837. removeScriptTypeAttributes: true,
  838. removeStyleLinkTypeAttributes: true,
  839. useShortDoctype: true,
  840. };
  841. try {
  842. html = require("html-minifier-terser").minify(html, minifyOptions);
  843. } catch (e) {
  844. const isParseError = String(e.message).indexOf("Parse Error") === 0;
  845. if (isParseError) {
  846. e.message =
  847. "html-webpack-plugin could not minify the generated output.\n" +
  848. "In production mode the html minification is enabled by default.\n" +
  849. "If you are not generating a valid html output please disable it manually.\n" +
  850. "You can do so by adding the following setting to your HtmlWebpackPlugin config:\n|\n|" +
  851. " minify: false\n|\n" +
  852. "See https://github.com/jantimon/html-webpack-plugin#options for details.\n\n" +
  853. "For parser dedicated bugs please create an issue here:\n" +
  854. "https://danielruf.github.io/html-minifier-terser/" +
  855. "\n" +
  856. e.message;
  857. }
  858. return Promise.reject(e);
  859. }
  860. return Promise.resolve(html);
  861. }
  862. /**
  863. * Helper to return a sorted unique array of all asset files out of the asset object
  864. * @private
  865. */
  866. getAssetFiles(assets) {
  867. const files = _uniq(
  868. Object.keys(assets)
  869. .filter((assetType) => assetType !== "chunks" && assets[assetType])
  870. .reduce((files, assetType) => files.concat(assets[assetType]), []),
  871. );
  872. files.sort();
  873. return files;
  874. }
  875. /**
  876. * Converts a favicon file from disk to a webpack resource and returns the url to the resource
  877. *
  878. * @private
  879. * @param {Compiler} compiler
  880. * @param {string|false} favicon
  881. * @param {Compilation} compilation
  882. * @param {string} publicPath
  883. * @param {PreviousEmittedAssets} previousEmittedAssets
  884. * @returns {Promise<string|undefined>}
  885. */
  886. generateFavicon(
  887. compiler,
  888. favicon,
  889. compilation,
  890. publicPath,
  891. previousEmittedAssets,
  892. ) {
  893. if (!favicon) {
  894. return Promise.resolve(undefined);
  895. }
  896. const filename = path.resolve(compilation.compiler.context, favicon);
  897. return promisify(compilation.inputFileSystem.readFile)(filename)
  898. .then((buf) => {
  899. const source = new compiler.webpack.sources.RawSource(
  900. /** @type {string | Buffer} */ (buf),
  901. false,
  902. );
  903. const name = path.basename(filename);
  904. compilation.fileDependencies.add(filename);
  905. compilation.emitAsset(name, source);
  906. previousEmittedAssets.push({ name, source });
  907. const faviconPath = publicPath + name;
  908. if (this.options.hash) {
  909. return this.appendHash(
  910. faviconPath,
  911. /** @type {string} */ (compilation.hash),
  912. );
  913. }
  914. return faviconPath;
  915. })
  916. .catch(() =>
  917. Promise.reject(
  918. new Error("HtmlWebpackPlugin: could not load file " + filename),
  919. ),
  920. );
  921. }
  922. /**
  923. * Generate all tags script for the given file paths
  924. *
  925. * @private
  926. * @param {Array<string>} jsAssets
  927. * @returns {Array<HtmlTagObject>}
  928. */
  929. generatedScriptTags(jsAssets) {
  930. // @ts-ignore
  931. return jsAssets.map((src) => {
  932. const attributes = {};
  933. if (this.options.scriptLoading === "defer") {
  934. attributes.defer = true;
  935. } else if (this.options.scriptLoading === "module") {
  936. attributes.type = "module";
  937. } else if (this.options.scriptLoading === "systemjs-module") {
  938. attributes.type = "systemjs-module";
  939. }
  940. attributes.src = src;
  941. return {
  942. tagName: "script",
  943. voidTag: false,
  944. meta: { plugin: "html-webpack-plugin" },
  945. attributes,
  946. };
  947. });
  948. }
  949. /**
  950. * Generate all style tags for the given file paths
  951. *
  952. * @private
  953. * @param {Array<string>} cssAssets
  954. * @returns {Array<HtmlTagObject>}
  955. */
  956. generateStyleTags(cssAssets) {
  957. return cssAssets.map((styleAsset) => ({
  958. tagName: "link",
  959. voidTag: true,
  960. meta: { plugin: "html-webpack-plugin" },
  961. attributes: {
  962. href: styleAsset,
  963. rel: "stylesheet",
  964. },
  965. }));
  966. }
  967. /**
  968. * Generate an optional base tag
  969. *
  970. * @param {string | {[attributeName: string]: string}} base
  971. * @returns {Array<HtmlTagObject>}
  972. */
  973. generateBaseTag(base) {
  974. return [
  975. {
  976. tagName: "base",
  977. voidTag: true,
  978. meta: { plugin: "html-webpack-plugin" },
  979. // attributes e.g. { href:"http://example.com/page.html" target:"_blank" }
  980. attributes:
  981. typeof base === "string"
  982. ? {
  983. href: base,
  984. }
  985. : base,
  986. },
  987. ];
  988. }
  989. /**
  990. * Generate all meta tags for the given meta configuration
  991. *
  992. * @private
  993. * @param {false | {[name: string]: false | string | {[attributeName: string]: string|boolean}}} metaOptions
  994. * @returns {Array<HtmlTagObject>}
  995. */
  996. generatedMetaTags(metaOptions) {
  997. if (metaOptions === false) {
  998. return [];
  999. }
  1000. // Make tags self-closing in case of xhtml
  1001. // Turn { "viewport" : "width=500, initial-scale=1" } into
  1002. // [{ name:"viewport" content:"width=500, initial-scale=1" }]
  1003. const metaTagAttributeObjects = Object.keys(metaOptions)
  1004. .map((metaName) => {
  1005. const metaTagContent = metaOptions[metaName];
  1006. return typeof metaTagContent === "string"
  1007. ? {
  1008. name: metaName,
  1009. content: metaTagContent,
  1010. }
  1011. : metaTagContent;
  1012. })
  1013. .filter((attribute) => attribute !== false);
  1014. // Turn [{ name:"viewport" content:"width=500, initial-scale=1" }] into
  1015. // the html-webpack-plugin tag structure
  1016. return metaTagAttributeObjects.map((metaTagAttributes) => {
  1017. if (metaTagAttributes === false) {
  1018. throw new Error("Invalid meta tag");
  1019. }
  1020. return {
  1021. tagName: "meta",
  1022. voidTag: true,
  1023. meta: { plugin: "html-webpack-plugin" },
  1024. attributes: metaTagAttributes,
  1025. };
  1026. });
  1027. }
  1028. /**
  1029. * Generate a favicon tag for the given file path
  1030. *
  1031. * @private
  1032. * @param {string} favicon
  1033. * @returns {Array<HtmlTagObject>}
  1034. */
  1035. generateFaviconTag(favicon) {
  1036. return [
  1037. {
  1038. tagName: "link",
  1039. voidTag: true,
  1040. meta: { plugin: "html-webpack-plugin" },
  1041. attributes: {
  1042. rel: "icon",
  1043. href: favicon,
  1044. },
  1045. },
  1046. ];
  1047. }
  1048. /**
  1049. * Group assets to head and body tags
  1050. *
  1051. * @param {{
  1052. scripts: Array<HtmlTagObject>;
  1053. styles: Array<HtmlTagObject>;
  1054. meta: Array<HtmlTagObject>;
  1055. }} assetTags
  1056. * @param {"body" | "head"} scriptTarget
  1057. * @returns {{
  1058. headTags: Array<HtmlTagObject>;
  1059. bodyTags: Array<HtmlTagObject>;
  1060. }}
  1061. */
  1062. groupAssetsByElements(assetTags, scriptTarget) {
  1063. /** @type {{ headTags: Array<HtmlTagObject>; bodyTags: Array<HtmlTagObject>; }} */
  1064. const result = {
  1065. headTags: [...assetTags.meta, ...assetTags.styles],
  1066. bodyTags: [],
  1067. };
  1068. // Add script tags to head or body depending on
  1069. // the htmlPluginOptions
  1070. if (scriptTarget === "body") {
  1071. result.bodyTags.push(...assetTags.scripts);
  1072. } else {
  1073. // If script loading is blocking add the scripts to the end of the head
  1074. // If script loading is non-blocking add the scripts in front of the css files
  1075. const insertPosition =
  1076. this.options.scriptLoading === "blocking"
  1077. ? result.headTags.length
  1078. : assetTags.meta.length;
  1079. result.headTags.splice(insertPosition, 0, ...assetTags.scripts);
  1080. }
  1081. return result;
  1082. }
  1083. /**
  1084. * Replace [contenthash] in filename
  1085. *
  1086. * @see https://survivejs.com/webpack/optimizing/adding-hashes-to-filenames/
  1087. *
  1088. * @private
  1089. * @param {Compiler} compiler
  1090. * @param {string} filename
  1091. * @param {string|Buffer} fileContent
  1092. * @param {Compilation} compilation
  1093. * @returns {{ path: string, info: {} }}
  1094. */
  1095. replacePlaceholdersInFilename(compiler, filename, fileContent, compilation) {
  1096. if (/\[\\*([\w:]+)\\*\]/i.test(filename) === false) {
  1097. return { path: filename, info: {} };
  1098. }
  1099. const hash = compiler.webpack.util.createHash(
  1100. compilation.outputOptions.hashFunction,
  1101. );
  1102. hash.update(fileContent);
  1103. if (compilation.outputOptions.hashSalt) {
  1104. hash.update(compilation.outputOptions.hashSalt);
  1105. }
  1106. const contentHash = /** @type {string} */ (
  1107. hash
  1108. .digest(compilation.outputOptions.hashDigest)
  1109. .slice(0, compilation.outputOptions.hashDigestLength)
  1110. );
  1111. return compilation.getPathWithInfo(filename, {
  1112. contentHash,
  1113. chunk: {
  1114. hash: contentHash,
  1115. // @ts-ignore
  1116. contentHash,
  1117. },
  1118. });
  1119. }
  1120. /**
  1121. * Function to generate HTML file.
  1122. *
  1123. * @private
  1124. * @param {Compiler} compiler
  1125. * @param {Compilation} compilation
  1126. * @param {string} outputName
  1127. * @param {CachedChildCompilation} childCompilerPlugin
  1128. * @param {PreviousEmittedAssets} previousEmittedAssets
  1129. * @param {{ value: string | undefined }} assetJson
  1130. * @param {(err?: Error) => void} callback
  1131. */
  1132. generateHTML(
  1133. compiler,
  1134. compilation,
  1135. outputName,
  1136. childCompilerPlugin,
  1137. previousEmittedAssets,
  1138. assetJson,
  1139. callback,
  1140. ) {
  1141. // Get all entry point names for this html file
  1142. const entryNames = Array.from(compilation.entrypoints.keys());
  1143. const filteredEntryNames = this.filterEntryChunks(
  1144. entryNames,
  1145. this.options.chunks,
  1146. this.options.excludeChunks,
  1147. );
  1148. const sortedEntryNames = this.sortEntryChunks(
  1149. filteredEntryNames,
  1150. this.options.chunksSortMode,
  1151. compilation,
  1152. );
  1153. const templateResult = this.options.templateContent
  1154. ? { mainCompilationHash: compilation.hash }
  1155. : childCompilerPlugin.getCompilationEntryResult(this.options.template);
  1156. if ("error" in templateResult) {
  1157. compilation.errors.push(
  1158. new Error(
  1159. prettyError(templateResult.error, compiler.context).toString(),
  1160. ),
  1161. );
  1162. }
  1163. // If the child compilation was not executed during a previous main compile run
  1164. // it is a cached result
  1165. const isCompilationCached =
  1166. templateResult.mainCompilationHash !== compilation.hash;
  1167. /** Generated file paths from the entry point names */
  1168. const assetsInformationByGroups = this.getAssetsInformationByGroups(
  1169. compilation,
  1170. outputName,
  1171. sortedEntryNames,
  1172. );
  1173. // If the template and the assets did not change we don't have to emit the html
  1174. const newAssetJson = JSON.stringify(
  1175. this.getAssetFiles(assetsInformationByGroups),
  1176. );
  1177. if (
  1178. isCompilationCached &&
  1179. this.options.cache &&
  1180. assetJson.value === newAssetJson
  1181. ) {
  1182. previousEmittedAssets.forEach(({ name, source, info }) => {
  1183. compilation.emitAsset(name, source, info);
  1184. });
  1185. return callback();
  1186. } else {
  1187. previousEmittedAssets.length = 0;
  1188. assetJson.value = newAssetJson;
  1189. }
  1190. // The html-webpack plugin uses a object representation for the html-tags which will be injected
  1191. // to allow altering them more easily
  1192. // Just before they are converted a third-party-plugin author might change the order and content
  1193. const assetsPromise = this.generateFavicon(
  1194. compiler,
  1195. this.options.favicon,
  1196. compilation,
  1197. assetsInformationByGroups.publicPath,
  1198. previousEmittedAssets,
  1199. ).then((faviconPath) => {
  1200. assetsInformationByGroups.favicon = faviconPath;
  1201. return HtmlWebpackPlugin.getCompilationHooks(
  1202. compilation,
  1203. ).beforeAssetTagGeneration.promise({
  1204. assets: assetsInformationByGroups,
  1205. outputName,
  1206. plugin: this,
  1207. });
  1208. });
  1209. // Turn the js and css paths into grouped HtmlTagObjects
  1210. const assetTagGroupsPromise = assetsPromise
  1211. // And allow third-party-plugin authors to reorder and change the assetTags before they are grouped
  1212. .then(({ assets }) =>
  1213. HtmlWebpackPlugin.getCompilationHooks(
  1214. compilation,
  1215. ).alterAssetTags.promise({
  1216. assetTags: {
  1217. scripts: this.generatedScriptTags(assets.js),
  1218. styles: this.generateStyleTags(assets.css),
  1219. meta: [
  1220. ...(this.options.base !== false
  1221. ? this.generateBaseTag(this.options.base)
  1222. : []),
  1223. ...this.generatedMetaTags(this.options.meta),
  1224. ...(assets.favicon
  1225. ? this.generateFaviconTag(assets.favicon)
  1226. : []),
  1227. ],
  1228. },
  1229. outputName,
  1230. publicPath: assetsInformationByGroups.publicPath,
  1231. plugin: this,
  1232. }),
  1233. )
  1234. .then(({ assetTags }) => {
  1235. // Inject scripts to body unless it set explicitly to head
  1236. const scriptTarget =
  1237. this.options.inject === "head" ||
  1238. (this.options.inject !== "body" &&
  1239. this.options.scriptLoading !== "blocking")
  1240. ? "head"
  1241. : "body";
  1242. // Group assets to `head` and `body` tag arrays
  1243. const assetGroups = this.groupAssetsByElements(assetTags, scriptTarget);
  1244. // Allow third-party-plugin authors to reorder and change the assetTags once they are grouped
  1245. return HtmlWebpackPlugin.getCompilationHooks(
  1246. compilation,
  1247. ).alterAssetTagGroups.promise({
  1248. headTags: assetGroups.headTags,
  1249. bodyTags: assetGroups.bodyTags,
  1250. outputName,
  1251. publicPath: assetsInformationByGroups.publicPath,
  1252. plugin: this,
  1253. });
  1254. });
  1255. // Turn the compiled template into a nodejs function or into a nodejs string
  1256. const templateEvaluationPromise = Promise.resolve().then(() => {
  1257. if ("error" in templateResult) {
  1258. return this.options.showErrors
  1259. ? prettyError(templateResult.error, compiler.context).toHtml()
  1260. : "ERROR";
  1261. }
  1262. // Allow to use a custom function / string instead
  1263. if (this.options.templateContent !== false) {
  1264. return this.options.templateContent;
  1265. }
  1266. // Once everything is compiled evaluate the html factory and replace it with its content
  1267. if ("compiledEntry" in templateResult) {
  1268. const compiledEntry = templateResult.compiledEntry;
  1269. const assets = compiledEntry.assets;
  1270. // Store assets from child compiler to re-emit them later
  1271. for (const name in assets) {
  1272. previousEmittedAssets.push({
  1273. name,
  1274. source: assets[name].source,
  1275. info: assets[name].info,
  1276. });
  1277. }
  1278. return this.evaluateCompilationResult(
  1279. compiledEntry.content,
  1280. assetsInformationByGroups.publicPath,
  1281. this.options.template,
  1282. );
  1283. }
  1284. return Promise.reject(
  1285. new Error("Child compilation contained no compiledEntry"),
  1286. );
  1287. });
  1288. const templateExecutionPromise = Promise.all([
  1289. assetsPromise,
  1290. assetTagGroupsPromise,
  1291. templateEvaluationPromise,
  1292. ])
  1293. // Execute the template
  1294. .then(([assetsHookResult, assetTags, compilationResult]) =>
  1295. typeof compilationResult !== "function"
  1296. ? compilationResult
  1297. : this.executeTemplate(
  1298. compilationResult,
  1299. assetsHookResult.assets,
  1300. { headTags: assetTags.headTags, bodyTags: assetTags.bodyTags },
  1301. compilation,
  1302. ),
  1303. );
  1304. const injectedHtmlPromise = Promise.all([
  1305. assetTagGroupsPromise,
  1306. templateExecutionPromise,
  1307. ])
  1308. // Allow plugins to change the html before assets are injected
  1309. .then(([assetTags, html]) => {
  1310. const pluginArgs = {
  1311. html,
  1312. headTags: assetTags.headTags,
  1313. bodyTags: assetTags.bodyTags,
  1314. plugin: this,
  1315. outputName,
  1316. };
  1317. return HtmlWebpackPlugin.getCompilationHooks(
  1318. compilation,
  1319. ).afterTemplateExecution.promise(pluginArgs);
  1320. })
  1321. .then(({ html, headTags, bodyTags }) => {
  1322. return this.postProcessHtml(compiler, html, assetsInformationByGroups, {
  1323. headTags,
  1324. bodyTags,
  1325. });
  1326. });
  1327. const emitHtmlPromise = injectedHtmlPromise
  1328. // Allow plugins to change the html after assets are injected
  1329. .then((html) => {
  1330. const pluginArgs = { html, plugin: this, outputName };
  1331. return HtmlWebpackPlugin.getCompilationHooks(compilation)
  1332. .beforeEmit.promise(pluginArgs)
  1333. .then((result) => result.html);
  1334. })
  1335. .catch((err) => {
  1336. // In case anything went wrong the promise is resolved
  1337. // with the error message and an error is logged
  1338. compilation.errors.push(
  1339. new Error(prettyError(err, compiler.context).toString()),
  1340. );
  1341. return this.options.showErrors
  1342. ? prettyError(err, compiler.context).toHtml()
  1343. : "ERROR";
  1344. })
  1345. .then((html) => {
  1346. const filename = outputName.replace(
  1347. /\[templatehash([^\]]*)\]/g,
  1348. require("util").deprecate(
  1349. (match, options) => `[contenthash${options}]`,
  1350. "[templatehash] is now [contenthash]",
  1351. ),
  1352. );
  1353. const replacedFilename = this.replacePlaceholdersInFilename(
  1354. compiler,
  1355. filename,
  1356. html,
  1357. compilation,
  1358. );
  1359. const source = new compiler.webpack.sources.RawSource(html, false);
  1360. // Add the evaluated html code to the webpack assets
  1361. compilation.emitAsset(
  1362. replacedFilename.path,
  1363. source,
  1364. replacedFilename.info,
  1365. );
  1366. previousEmittedAssets.push({ name: replacedFilename.path, source });
  1367. return replacedFilename.path;
  1368. })
  1369. .then((finalOutputName) =>
  1370. HtmlWebpackPlugin.getCompilationHooks(compilation)
  1371. .afterEmit.promise({
  1372. outputName: finalOutputName,
  1373. plugin: this,
  1374. })
  1375. .catch((err) => {
  1376. /** @type {Logger} */
  1377. (this.logger).error(err);
  1378. return null;
  1379. })
  1380. .then(() => null),
  1381. );
  1382. // Once all files are added to the webpack compilation
  1383. // let the webpack compiler continue
  1384. emitHtmlPromise.then(() => {
  1385. callback();
  1386. });
  1387. }
  1388. }
  1389. /**
  1390. * The default for options.templateParameter
  1391. * Generate the template parameters
  1392. *
  1393. * Generate the template parameters for the template function
  1394. * @param {Compilation} compilation
  1395. * @param {AssetsInformationByGroups} assets
  1396. * @param {{
  1397. headTags: HtmlTagObject[],
  1398. bodyTags: HtmlTagObject[]
  1399. }} assetTags
  1400. * @param {ProcessedHtmlWebpackOptions} options
  1401. * @returns {TemplateParameter}
  1402. */
  1403. function templateParametersGenerator(compilation, assets, assetTags, options) {
  1404. return {
  1405. compilation: compilation,
  1406. webpackConfig: compilation.options,
  1407. htmlWebpackPlugin: {
  1408. tags: assetTags,
  1409. files: assets,
  1410. options: options,
  1411. },
  1412. };
  1413. }
  1414. // Statics:
  1415. /**
  1416. * The major version number of this plugin
  1417. */
  1418. HtmlWebpackPlugin.version = 5;
  1419. /**
  1420. * A static helper to get the hooks for this plugin
  1421. *
  1422. * Usage: HtmlWebpackPlugin.getHooks(compilation).HOOK_NAME.tapAsync('YourPluginName', () => { ... });
  1423. */
  1424. // TODO remove me in the next major release in favor getCompilationHooks
  1425. HtmlWebpackPlugin.getHooks = HtmlWebpackPlugin.getCompilationHooks;
  1426. HtmlWebpackPlugin.createHtmlTagObject = createHtmlTagObject;
  1427. module.exports = HtmlWebpackPlugin;