index.js 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  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 vmContext = vm.createContext({
  578. ...global,
  579. HTML_WEBPACK_PLUGIN: true,
  580. require: require,
  581. htmlWebpackPluginPublicPath: publicPath,
  582. __filename: templateWithoutLoaders,
  583. __dirname: path.dirname(templateWithoutLoaders),
  584. AbortController: global.AbortController,
  585. AbortSignal: global.AbortSignal,
  586. Blob: global.Blob,
  587. Buffer: global.Buffer,
  588. ByteLengthQueuingStrategy: global.ByteLengthQueuingStrategy,
  589. BroadcastChannel: global.BroadcastChannel,
  590. CompressionStream: global.CompressionStream,
  591. CountQueuingStrategy: global.CountQueuingStrategy,
  592. Crypto: global.Crypto,
  593. CryptoKey: global.CryptoKey,
  594. CustomEvent: global.CustomEvent,
  595. DecompressionStream: global.DecompressionStream,
  596. Event: global.Event,
  597. EventTarget: global.EventTarget,
  598. File: global.File,
  599. FormData: global.FormData,
  600. Headers: global.Headers,
  601. MessageChannel: global.MessageChannel,
  602. MessageEvent: global.MessageEvent,
  603. MessagePort: global.MessagePort,
  604. PerformanceEntry: global.PerformanceEntry,
  605. PerformanceMark: global.PerformanceMark,
  606. PerformanceMeasure: global.PerformanceMeasure,
  607. PerformanceObserver: global.PerformanceObserver,
  608. PerformanceObserverEntryList: global.PerformanceObserverEntryList,
  609. PerformanceResourceTiming: global.PerformanceResourceTiming,
  610. ReadableByteStreamController: global.ReadableByteStreamController,
  611. ReadableStream: global.ReadableStream,
  612. ReadableStreamBYOBReader: global.ReadableStreamBYOBReader,
  613. ReadableStreamBYOBRequest: global.ReadableStreamBYOBRequest,
  614. ReadableStreamDefaultController: global.ReadableStreamDefaultController,
  615. ReadableStreamDefaultReader: global.ReadableStreamDefaultReader,
  616. Response: global.Response,
  617. Request: global.Request,
  618. SubtleCrypto: global.SubtleCrypto,
  619. DOMException: global.DOMException,
  620. TextDecoder: global.TextDecoder,
  621. TextDecoderStream: global.TextDecoderStream,
  622. TextEncoder: global.TextEncoder,
  623. TextEncoderStream: global.TextEncoderStream,
  624. TransformStream: global.TransformStream,
  625. TransformStreamDefaultController: global.TransformStreamDefaultController,
  626. URL: global.URL,
  627. URLSearchParams: global.URLSearchParams,
  628. WebAssembly: global.WebAssembly,
  629. WritableStream: global.WritableStream,
  630. WritableStreamDefaultController: global.WritableStreamDefaultController,
  631. WritableStreamDefaultWriter: global.WritableStreamDefaultWriter,
  632. });
  633. const vmScript = new vm.Script(source, {
  634. filename: templateWithoutLoaders,
  635. });
  636. // Evaluate code and cast to string
  637. let newSource;
  638. try {
  639. newSource = vmScript.runInContext(vmContext);
  640. } catch (e) {
  641. return Promise.reject(e);
  642. }
  643. if (
  644. typeof newSource === "object" &&
  645. newSource.__esModule &&
  646. newSource.default !== undefined
  647. ) {
  648. newSource = newSource.default;
  649. }
  650. return typeof newSource === "string" || typeof newSource === "function"
  651. ? Promise.resolve(newSource)
  652. : Promise.reject(
  653. new Error(
  654. 'The loader "' + templateWithoutLoaders + "\" didn't return html.",
  655. ),
  656. );
  657. }
  658. /**
  659. * Add toString methods for easier rendering inside the template
  660. *
  661. * @private
  662. * @param {Array<HtmlTagObject>} assetTagGroup
  663. * @returns {Array<HtmlTagObject>}
  664. */
  665. prepareAssetTagGroupForRendering(assetTagGroup) {
  666. const xhtml = this.options.xhtml;
  667. return HtmlTagArray.from(
  668. assetTagGroup.map((assetTag) => {
  669. const copiedAssetTag = Object.assign({}, assetTag);
  670. copiedAssetTag.toString = function () {
  671. return htmlTagObjectToString(this, xhtml);
  672. };
  673. return copiedAssetTag;
  674. }),
  675. );
  676. }
  677. /**
  678. * Generate the template parameters for the template function
  679. *
  680. * @private
  681. * @param {Compilation} compilation
  682. * @param {AssetsInformationByGroups} assetsInformationByGroups
  683. * @param {{
  684. headTags: HtmlTagObject[],
  685. bodyTags: HtmlTagObject[]
  686. }} assetTags
  687. * @returns {Promise<{[key: any]: any}>}
  688. */
  689. getTemplateParameters(compilation, assetsInformationByGroups, assetTags) {
  690. const templateParameters = this.options.templateParameters;
  691. if (templateParameters === false) {
  692. return Promise.resolve({});
  693. }
  694. if (
  695. typeof templateParameters !== "function" &&
  696. typeof templateParameters !== "object"
  697. ) {
  698. throw new Error(
  699. "templateParameters has to be either a function or an object",
  700. );
  701. }
  702. const templateParameterFunction =
  703. typeof templateParameters === "function"
  704. ? // A custom function can overwrite the entire template parameter preparation
  705. templateParameters
  706. : // If the template parameters is an object merge it with the default values
  707. (compilation, assetsInformationByGroups, assetTags, options) =>
  708. Object.assign(
  709. {},
  710. templateParametersGenerator(
  711. compilation,
  712. assetsInformationByGroups,
  713. assetTags,
  714. options,
  715. ),
  716. templateParameters,
  717. );
  718. const preparedAssetTags = {
  719. headTags: this.prepareAssetTagGroupForRendering(assetTags.headTags),
  720. bodyTags: this.prepareAssetTagGroupForRendering(assetTags.bodyTags),
  721. };
  722. return Promise.resolve().then(() =>
  723. templateParameterFunction(
  724. compilation,
  725. assetsInformationByGroups,
  726. preparedAssetTags,
  727. this.options,
  728. ),
  729. );
  730. }
  731. /**
  732. * This function renders the actual html by executing the template function
  733. *
  734. * @private
  735. * @param {(templateParameters) => string | Promise<string>} templateFunction
  736. * @param {AssetsInformationByGroups} assetsInformationByGroups
  737. * @param {{
  738. headTags: HtmlTagObject[],
  739. bodyTags: HtmlTagObject[]
  740. }} assetTags
  741. * @param {Compilation} compilation
  742. * @returns Promise<string>
  743. */
  744. executeTemplate(
  745. templateFunction,
  746. assetsInformationByGroups,
  747. assetTags,
  748. compilation,
  749. ) {
  750. // Template processing
  751. const templateParamsPromise = this.getTemplateParameters(
  752. compilation,
  753. assetsInformationByGroups,
  754. assetTags,
  755. );
  756. return templateParamsPromise.then((templateParams) => {
  757. try {
  758. // If html is a promise return the promise
  759. // If html is a string turn it into a promise
  760. return templateFunction(templateParams);
  761. } catch (e) {
  762. // @ts-ignore
  763. compilation.errors.push(new Error("Template execution failed: " + e));
  764. return Promise.reject(e);
  765. }
  766. });
  767. }
  768. /**
  769. * Html Post processing
  770. *
  771. * @private
  772. * @param {Compiler} compiler The compiler instance
  773. * @param {any} originalHtml The input html
  774. * @param {AssetsInformationByGroups} assetsInformationByGroups
  775. * @param {{headTags: HtmlTagObject[], bodyTags: HtmlTagObject[]}} assetTags The asset tags to inject
  776. * @returns {Promise<string>}
  777. */
  778. postProcessHtml(
  779. compiler,
  780. originalHtml,
  781. assetsInformationByGroups,
  782. assetTags,
  783. ) {
  784. let html = originalHtml;
  785. if (typeof html !== "string") {
  786. return Promise.reject(
  787. new Error(
  788. "Expected html to be a string but got " + JSON.stringify(html),
  789. ),
  790. );
  791. }
  792. if (this.options.inject) {
  793. const htmlRegExp = /(<html[^>]*>)/i;
  794. const headRegExp = /(<\/head\s*>)/i;
  795. const bodyRegExp = /(<\/body\s*>)/i;
  796. const metaViewportRegExp = /<meta[^>]+name=["']viewport["'][^>]*>/i;
  797. const body = assetTags.bodyTags.map((assetTagObject) =>
  798. htmlTagObjectToString(assetTagObject, this.options.xhtml),
  799. );
  800. const head = assetTags.headTags
  801. .filter((item) => {
  802. if (
  803. item.tagName === "meta" &&
  804. item.attributes &&
  805. item.attributes.name === "viewport" &&
  806. metaViewportRegExp.test(html)
  807. ) {
  808. return false;
  809. }
  810. return true;
  811. })
  812. .map((assetTagObject) =>
  813. htmlTagObjectToString(assetTagObject, this.options.xhtml),
  814. );
  815. if (body.length) {
  816. if (bodyRegExp.test(html)) {
  817. // Append assets to body element
  818. html = html.replace(bodyRegExp, (match) => body.join("") + match);
  819. } else {
  820. // Append scripts to the end of the file if no <body> element exists:
  821. html += body.join("");
  822. }
  823. }
  824. if (head.length) {
  825. // Create a head tag if none exists
  826. if (!headRegExp.test(html)) {
  827. if (!htmlRegExp.test(html)) {
  828. html = "<head></head>" + html;
  829. } else {
  830. html = html.replace(htmlRegExp, (match) => match + "<head></head>");
  831. }
  832. }
  833. // Append assets to head element
  834. html = html.replace(headRegExp, (match) => head.join("") + match);
  835. }
  836. // Inject manifest into the opening html tag
  837. if (assetsInformationByGroups.manifest) {
  838. html = html.replace(/(<html[^>]*)(>)/i, (match, start, end) => {
  839. // Append the manifest only if no manifest was specified
  840. if (/\smanifest\s*=/.test(match)) {
  841. return match;
  842. }
  843. return (
  844. start +
  845. ' manifest="' +
  846. assetsInformationByGroups.manifest +
  847. '"' +
  848. end
  849. );
  850. });
  851. }
  852. }
  853. // TODO avoid this logic and use https://github.com/webpack-contrib/html-minimizer-webpack-plugin under the hood in the next major version
  854. // Check if webpack is running in production mode
  855. // @see https://github.com/webpack/webpack/blob/3366421f1784c449f415cda5930a8e445086f688/lib/WebpackOptionsDefaulter.js#L12-L14
  856. const isProductionLikeMode =
  857. compiler.options.mode === "production" || !compiler.options.mode;
  858. const needMinify =
  859. this.options.minify === true ||
  860. typeof this.options.minify === "object" ||
  861. (this.options.minify === "auto" && isProductionLikeMode);
  862. if (!needMinify) {
  863. return Promise.resolve(html);
  864. }
  865. const minifyOptions =
  866. typeof this.options.minify === "object"
  867. ? this.options.minify
  868. : {
  869. // https://www.npmjs.com/package/html-minifier-terser#options-quick-reference
  870. collapseWhitespace: true,
  871. keepClosingSlash: true,
  872. removeComments: true,
  873. removeRedundantAttributes: true,
  874. removeScriptTypeAttributes: true,
  875. removeStyleLinkTypeAttributes: true,
  876. useShortDoctype: true,
  877. };
  878. try {
  879. html = require("html-minifier-terser").minify(html, minifyOptions);
  880. } catch (e) {
  881. const isParseError = String(e.message).indexOf("Parse Error") === 0;
  882. if (isParseError) {
  883. e.message =
  884. "html-webpack-plugin could not minify the generated output.\n" +
  885. "In production mode the html minification is enabled by default.\n" +
  886. "If you are not generating a valid html output please disable it manually.\n" +
  887. "You can do so by adding the following setting to your HtmlWebpackPlugin config:\n|\n|" +
  888. " minify: false\n|\n" +
  889. "See https://github.com/jantimon/html-webpack-plugin#options for details.\n\n" +
  890. "For parser dedicated bugs please create an issue here:\n" +
  891. "https://danielruf.github.io/html-minifier-terser/" +
  892. "\n" +
  893. e.message;
  894. }
  895. return Promise.reject(e);
  896. }
  897. return Promise.resolve(html);
  898. }
  899. /**
  900. * Helper to return a sorted unique array of all asset files out of the asset object
  901. * @private
  902. */
  903. getAssetFiles(assets) {
  904. const files = _uniq(
  905. Object.keys(assets)
  906. .filter((assetType) => assetType !== "chunks" && assets[assetType])
  907. .reduce((files, assetType) => files.concat(assets[assetType]), []),
  908. );
  909. files.sort();
  910. return files;
  911. }
  912. /**
  913. * Converts a favicon file from disk to a webpack resource and returns the url to the resource
  914. *
  915. * @private
  916. * @param {Compiler} compiler
  917. * @param {string|false} favicon
  918. * @param {Compilation} compilation
  919. * @param {string} publicPath
  920. * @param {PreviousEmittedAssets} previousEmittedAssets
  921. * @returns {Promise<string|undefined>}
  922. */
  923. generateFavicon(
  924. compiler,
  925. favicon,
  926. compilation,
  927. publicPath,
  928. previousEmittedAssets,
  929. ) {
  930. if (!favicon) {
  931. return Promise.resolve(undefined);
  932. }
  933. const filename = path.resolve(compilation.compiler.context, favicon);
  934. return promisify(compilation.inputFileSystem.readFile)(filename)
  935. .then((buf) => {
  936. const source = new compiler.webpack.sources.RawSource(
  937. /** @type {string | Buffer} */ (buf),
  938. false,
  939. );
  940. const name = path.basename(filename);
  941. compilation.fileDependencies.add(filename);
  942. compilation.emitAsset(name, source);
  943. previousEmittedAssets.push({ name, source });
  944. const faviconPath = publicPath + name;
  945. if (this.options.hash) {
  946. return this.appendHash(
  947. faviconPath,
  948. /** @type {string} */ (compilation.hash),
  949. );
  950. }
  951. return faviconPath;
  952. })
  953. .catch(() =>
  954. Promise.reject(
  955. new Error("HtmlWebpackPlugin: could not load file " + filename),
  956. ),
  957. );
  958. }
  959. /**
  960. * Generate all tags script for the given file paths
  961. *
  962. * @private
  963. * @param {Array<string>} jsAssets
  964. * @returns {Array<HtmlTagObject>}
  965. */
  966. generatedScriptTags(jsAssets) {
  967. // @ts-ignore
  968. return jsAssets.map((src) => {
  969. const attributes = {};
  970. if (this.options.scriptLoading === "defer") {
  971. attributes.defer = true;
  972. } else if (this.options.scriptLoading === "module") {
  973. attributes.type = "module";
  974. } else if (this.options.scriptLoading === "systemjs-module") {
  975. attributes.type = "systemjs-module";
  976. }
  977. attributes.src = src;
  978. return {
  979. tagName: "script",
  980. voidTag: false,
  981. meta: { plugin: "html-webpack-plugin" },
  982. attributes,
  983. };
  984. });
  985. }
  986. /**
  987. * Generate all style tags for the given file paths
  988. *
  989. * @private
  990. * @param {Array<string>} cssAssets
  991. * @returns {Array<HtmlTagObject>}
  992. */
  993. generateStyleTags(cssAssets) {
  994. return cssAssets.map((styleAsset) => ({
  995. tagName: "link",
  996. voidTag: true,
  997. meta: { plugin: "html-webpack-plugin" },
  998. attributes: {
  999. href: styleAsset,
  1000. rel: "stylesheet",
  1001. },
  1002. }));
  1003. }
  1004. /**
  1005. * Generate an optional base tag
  1006. *
  1007. * @param {string | {[attributeName: string]: string}} base
  1008. * @returns {Array<HtmlTagObject>}
  1009. */
  1010. generateBaseTag(base) {
  1011. return [
  1012. {
  1013. tagName: "base",
  1014. voidTag: true,
  1015. meta: { plugin: "html-webpack-plugin" },
  1016. // attributes e.g. { href:"http://example.com/page.html" target:"_blank" }
  1017. attributes:
  1018. typeof base === "string"
  1019. ? {
  1020. href: base,
  1021. }
  1022. : base,
  1023. },
  1024. ];
  1025. }
  1026. /**
  1027. * Generate all meta tags for the given meta configuration
  1028. *
  1029. * @private
  1030. * @param {false | {[name: string]: false | string | {[attributeName: string]: string|boolean}}} metaOptions
  1031. * @returns {Array<HtmlTagObject>}
  1032. */
  1033. generatedMetaTags(metaOptions) {
  1034. if (metaOptions === false) {
  1035. return [];
  1036. }
  1037. // Make tags self-closing in case of xhtml
  1038. // Turn { "viewport" : "width=500, initial-scale=1" } into
  1039. // [{ name:"viewport" content:"width=500, initial-scale=1" }]
  1040. const metaTagAttributeObjects = Object.keys(metaOptions)
  1041. .map((metaName) => {
  1042. const metaTagContent = metaOptions[metaName];
  1043. return typeof metaTagContent === "string"
  1044. ? {
  1045. name: metaName,
  1046. content: metaTagContent,
  1047. }
  1048. : metaTagContent;
  1049. })
  1050. .filter((attribute) => attribute !== false);
  1051. // Turn [{ name:"viewport" content:"width=500, initial-scale=1" }] into
  1052. // the html-webpack-plugin tag structure
  1053. return metaTagAttributeObjects.map((metaTagAttributes) => {
  1054. if (metaTagAttributes === false) {
  1055. throw new Error("Invalid meta tag");
  1056. }
  1057. return {
  1058. tagName: "meta",
  1059. voidTag: true,
  1060. meta: { plugin: "html-webpack-plugin" },
  1061. attributes: metaTagAttributes,
  1062. };
  1063. });
  1064. }
  1065. /**
  1066. * Generate a favicon tag for the given file path
  1067. *
  1068. * @private
  1069. * @param {string} favicon
  1070. * @returns {Array<HtmlTagObject>}
  1071. */
  1072. generateFaviconTag(favicon) {
  1073. return [
  1074. {
  1075. tagName: "link",
  1076. voidTag: true,
  1077. meta: { plugin: "html-webpack-plugin" },
  1078. attributes: {
  1079. rel: "icon",
  1080. href: favicon,
  1081. },
  1082. },
  1083. ];
  1084. }
  1085. /**
  1086. * Group assets to head and body tags
  1087. *
  1088. * @param {{
  1089. scripts: Array<HtmlTagObject>;
  1090. styles: Array<HtmlTagObject>;
  1091. meta: Array<HtmlTagObject>;
  1092. }} assetTags
  1093. * @param {"body" | "head"} scriptTarget
  1094. * @returns {{
  1095. headTags: Array<HtmlTagObject>;
  1096. bodyTags: Array<HtmlTagObject>;
  1097. }}
  1098. */
  1099. groupAssetsByElements(assetTags, scriptTarget) {
  1100. /** @type {{ headTags: Array<HtmlTagObject>; bodyTags: Array<HtmlTagObject>; }} */
  1101. const result = {
  1102. headTags: [...assetTags.meta, ...assetTags.styles],
  1103. bodyTags: [],
  1104. };
  1105. // Add script tags to head or body depending on
  1106. // the htmlPluginOptions
  1107. if (scriptTarget === "body") {
  1108. result.bodyTags.push(...assetTags.scripts);
  1109. } else {
  1110. // If script loading is blocking add the scripts to the end of the head
  1111. // If script loading is non-blocking add the scripts in front of the css files
  1112. const insertPosition =
  1113. this.options.scriptLoading === "blocking"
  1114. ? result.headTags.length
  1115. : assetTags.meta.length;
  1116. result.headTags.splice(insertPosition, 0, ...assetTags.scripts);
  1117. }
  1118. return result;
  1119. }
  1120. /**
  1121. * Replace [contenthash] in filename
  1122. *
  1123. * @see https://survivejs.com/webpack/optimizing/adding-hashes-to-filenames/
  1124. *
  1125. * @private
  1126. * @param {Compiler} compiler
  1127. * @param {string} filename
  1128. * @param {string|Buffer} fileContent
  1129. * @param {Compilation} compilation
  1130. * @returns {{ path: string, info: {} }}
  1131. */
  1132. replacePlaceholdersInFilename(compiler, filename, fileContent, compilation) {
  1133. if (/\[\\*([\w:]+)\\*\]/i.test(filename) === false) {
  1134. return { path: filename, info: {} };
  1135. }
  1136. const hash = compiler.webpack.util.createHash(
  1137. compilation.outputOptions.hashFunction,
  1138. );
  1139. hash.update(fileContent);
  1140. if (compilation.outputOptions.hashSalt) {
  1141. hash.update(compilation.outputOptions.hashSalt);
  1142. }
  1143. const contentHash = /** @type {string} */ (
  1144. hash
  1145. .digest(compilation.outputOptions.hashDigest)
  1146. .slice(0, compilation.outputOptions.hashDigestLength)
  1147. );
  1148. return compilation.getPathWithInfo(filename, {
  1149. contentHash,
  1150. chunk: {
  1151. hash: contentHash,
  1152. // @ts-ignore
  1153. contentHash,
  1154. },
  1155. });
  1156. }
  1157. /**
  1158. * Function to generate HTML file.
  1159. *
  1160. * @private
  1161. * @param {Compiler} compiler
  1162. * @param {Compilation} compilation
  1163. * @param {string} outputName
  1164. * @param {CachedChildCompilation} childCompilerPlugin
  1165. * @param {PreviousEmittedAssets} previousEmittedAssets
  1166. * @param {{ value: string | undefined }} assetJson
  1167. * @param {(err?: Error) => void} callback
  1168. */
  1169. generateHTML(
  1170. compiler,
  1171. compilation,
  1172. outputName,
  1173. childCompilerPlugin,
  1174. previousEmittedAssets,
  1175. assetJson,
  1176. callback,
  1177. ) {
  1178. // Get all entry point names for this html file
  1179. const entryNames = Array.from(compilation.entrypoints.keys());
  1180. const filteredEntryNames = this.filterEntryChunks(
  1181. entryNames,
  1182. this.options.chunks,
  1183. this.options.excludeChunks,
  1184. );
  1185. const sortedEntryNames = this.sortEntryChunks(
  1186. filteredEntryNames,
  1187. this.options.chunksSortMode,
  1188. compilation,
  1189. );
  1190. const templateResult = this.options.templateContent
  1191. ? { mainCompilationHash: compilation.hash }
  1192. : childCompilerPlugin.getCompilationEntryResult(this.options.template);
  1193. if ("error" in templateResult) {
  1194. compilation.errors.push(
  1195. prettyError(templateResult.error, compiler.context).toString(),
  1196. );
  1197. }
  1198. // If the child compilation was not executed during a previous main compile run
  1199. // it is a cached result
  1200. const isCompilationCached =
  1201. templateResult.mainCompilationHash !== compilation.hash;
  1202. /** Generated file paths from the entry point names */
  1203. const assetsInformationByGroups = this.getAssetsInformationByGroups(
  1204. compilation,
  1205. outputName,
  1206. sortedEntryNames,
  1207. );
  1208. // If the template and the assets did not change we don't have to emit the html
  1209. const newAssetJson = JSON.stringify(
  1210. this.getAssetFiles(assetsInformationByGroups),
  1211. );
  1212. if (
  1213. isCompilationCached &&
  1214. this.options.cache &&
  1215. assetJson.value === newAssetJson
  1216. ) {
  1217. previousEmittedAssets.forEach(({ name, source, info }) => {
  1218. compilation.emitAsset(name, source, info);
  1219. });
  1220. return callback();
  1221. } else {
  1222. previousEmittedAssets.length = 0;
  1223. assetJson.value = newAssetJson;
  1224. }
  1225. // The html-webpack plugin uses a object representation for the html-tags which will be injected
  1226. // to allow altering them more easily
  1227. // Just before they are converted a third-party-plugin author might change the order and content
  1228. const assetsPromise = this.generateFavicon(
  1229. compiler,
  1230. this.options.favicon,
  1231. compilation,
  1232. assetsInformationByGroups.publicPath,
  1233. previousEmittedAssets,
  1234. ).then((faviconPath) => {
  1235. assetsInformationByGroups.favicon = faviconPath;
  1236. return HtmlWebpackPlugin.getCompilationHooks(
  1237. compilation,
  1238. ).beforeAssetTagGeneration.promise({
  1239. assets: assetsInformationByGroups,
  1240. outputName,
  1241. plugin: this,
  1242. });
  1243. });
  1244. // Turn the js and css paths into grouped HtmlTagObjects
  1245. const assetTagGroupsPromise = assetsPromise
  1246. // And allow third-party-plugin authors to reorder and change the assetTags before they are grouped
  1247. .then(({ assets }) =>
  1248. HtmlWebpackPlugin.getCompilationHooks(
  1249. compilation,
  1250. ).alterAssetTags.promise({
  1251. assetTags: {
  1252. scripts: this.generatedScriptTags(assets.js),
  1253. styles: this.generateStyleTags(assets.css),
  1254. meta: [
  1255. ...(this.options.base !== false
  1256. ? this.generateBaseTag(this.options.base)
  1257. : []),
  1258. ...this.generatedMetaTags(this.options.meta),
  1259. ...(assets.favicon
  1260. ? this.generateFaviconTag(assets.favicon)
  1261. : []),
  1262. ],
  1263. },
  1264. outputName,
  1265. publicPath: assetsInformationByGroups.publicPath,
  1266. plugin: this,
  1267. }),
  1268. )
  1269. .then(({ assetTags }) => {
  1270. // Inject scripts to body unless it set explicitly to head
  1271. const scriptTarget =
  1272. this.options.inject === "head" ||
  1273. (this.options.inject !== "body" &&
  1274. this.options.scriptLoading !== "blocking")
  1275. ? "head"
  1276. : "body";
  1277. // Group assets to `head` and `body` tag arrays
  1278. const assetGroups = this.groupAssetsByElements(assetTags, scriptTarget);
  1279. // Allow third-party-plugin authors to reorder and change the assetTags once they are grouped
  1280. return HtmlWebpackPlugin.getCompilationHooks(
  1281. compilation,
  1282. ).alterAssetTagGroups.promise({
  1283. headTags: assetGroups.headTags,
  1284. bodyTags: assetGroups.bodyTags,
  1285. outputName,
  1286. publicPath: assetsInformationByGroups.publicPath,
  1287. plugin: this,
  1288. });
  1289. });
  1290. // Turn the compiled template into a nodejs function or into a nodejs string
  1291. const templateEvaluationPromise = Promise.resolve().then(() => {
  1292. if ("error" in templateResult) {
  1293. return this.options.showErrors
  1294. ? prettyError(templateResult.error, compiler.context).toHtml()
  1295. : "ERROR";
  1296. }
  1297. // Allow to use a custom function / string instead
  1298. if (this.options.templateContent !== false) {
  1299. return this.options.templateContent;
  1300. }
  1301. // Once everything is compiled evaluate the html factory and replace it with its content
  1302. if ("compiledEntry" in templateResult) {
  1303. const compiledEntry = templateResult.compiledEntry;
  1304. const assets = compiledEntry.assets;
  1305. // Store assets from child compiler to re-emit them later
  1306. for (const name in assets) {
  1307. previousEmittedAssets.push({
  1308. name,
  1309. source: assets[name].source,
  1310. info: assets[name].info,
  1311. });
  1312. }
  1313. return this.evaluateCompilationResult(
  1314. compiledEntry.content,
  1315. assetsInformationByGroups.publicPath,
  1316. this.options.template,
  1317. );
  1318. }
  1319. return Promise.reject(
  1320. new Error("Child compilation contained no compiledEntry"),
  1321. );
  1322. });
  1323. const templateExecutionPromise = Promise.all([
  1324. assetsPromise,
  1325. assetTagGroupsPromise,
  1326. templateEvaluationPromise,
  1327. ])
  1328. // Execute the template
  1329. .then(([assetsHookResult, assetTags, compilationResult]) =>
  1330. typeof compilationResult !== "function"
  1331. ? compilationResult
  1332. : this.executeTemplate(
  1333. compilationResult,
  1334. assetsHookResult.assets,
  1335. { headTags: assetTags.headTags, bodyTags: assetTags.bodyTags },
  1336. compilation,
  1337. ),
  1338. );
  1339. const injectedHtmlPromise = Promise.all([
  1340. assetTagGroupsPromise,
  1341. templateExecutionPromise,
  1342. ])
  1343. // Allow plugins to change the html before assets are injected
  1344. .then(([assetTags, html]) => {
  1345. const pluginArgs = {
  1346. html,
  1347. headTags: assetTags.headTags,
  1348. bodyTags: assetTags.bodyTags,
  1349. plugin: this,
  1350. outputName,
  1351. };
  1352. return HtmlWebpackPlugin.getCompilationHooks(
  1353. compilation,
  1354. ).afterTemplateExecution.promise(pluginArgs);
  1355. })
  1356. .then(({ html, headTags, bodyTags }) => {
  1357. return this.postProcessHtml(compiler, html, assetsInformationByGroups, {
  1358. headTags,
  1359. bodyTags,
  1360. });
  1361. });
  1362. const emitHtmlPromise = injectedHtmlPromise
  1363. // Allow plugins to change the html after assets are injected
  1364. .then((html) => {
  1365. const pluginArgs = { html, plugin: this, outputName };
  1366. return HtmlWebpackPlugin.getCompilationHooks(compilation)
  1367. .beforeEmit.promise(pluginArgs)
  1368. .then((result) => result.html);
  1369. })
  1370. .catch((err) => {
  1371. // In case anything went wrong the promise is resolved
  1372. // with the error message and an error is logged
  1373. compilation.errors.push(prettyError(err, compiler.context).toString());
  1374. return this.options.showErrors
  1375. ? prettyError(err, compiler.context).toHtml()
  1376. : "ERROR";
  1377. })
  1378. .then((html) => {
  1379. const filename = outputName.replace(
  1380. /\[templatehash([^\]]*)\]/g,
  1381. require("util").deprecate(
  1382. (match, options) => `[contenthash${options}]`,
  1383. "[templatehash] is now [contenthash]",
  1384. ),
  1385. );
  1386. const replacedFilename = this.replacePlaceholdersInFilename(
  1387. compiler,
  1388. filename,
  1389. html,
  1390. compilation,
  1391. );
  1392. const source = new compiler.webpack.sources.RawSource(html, false);
  1393. // Add the evaluated html code to the webpack assets
  1394. compilation.emitAsset(
  1395. replacedFilename.path,
  1396. source,
  1397. replacedFilename.info,
  1398. );
  1399. previousEmittedAssets.push({ name: replacedFilename.path, source });
  1400. return replacedFilename.path;
  1401. })
  1402. .then((finalOutputName) =>
  1403. HtmlWebpackPlugin.getCompilationHooks(compilation)
  1404. .afterEmit.promise({
  1405. outputName: finalOutputName,
  1406. plugin: this,
  1407. })
  1408. .catch((err) => {
  1409. /** @type {Logger} */
  1410. (this.logger).error(err);
  1411. return null;
  1412. })
  1413. .then(() => null),
  1414. );
  1415. // Once all files are added to the webpack compilation
  1416. // let the webpack compiler continue
  1417. emitHtmlPromise.then(() => {
  1418. callback();
  1419. });
  1420. }
  1421. }
  1422. /**
  1423. * The default for options.templateParameter
  1424. * Generate the template parameters
  1425. *
  1426. * Generate the template parameters for the template function
  1427. * @param {Compilation} compilation
  1428. * @param {AssetsInformationByGroups} assets
  1429. * @param {{
  1430. headTags: HtmlTagObject[],
  1431. bodyTags: HtmlTagObject[]
  1432. }} assetTags
  1433. * @param {ProcessedHtmlWebpackOptions} options
  1434. * @returns {TemplateParameter}
  1435. */
  1436. function templateParametersGenerator(compilation, assets, assetTags, options) {
  1437. return {
  1438. compilation: compilation,
  1439. webpackConfig: compilation.options,
  1440. htmlWebpackPlugin: {
  1441. tags: assetTags,
  1442. files: assets,
  1443. options: options,
  1444. },
  1445. };
  1446. }
  1447. // Statics:
  1448. /**
  1449. * The major version number of this plugin
  1450. */
  1451. HtmlWebpackPlugin.version = 5;
  1452. /**
  1453. * A static helper to get the hooks for this plugin
  1454. *
  1455. * Usage: HtmlWebpackPlugin.getHooks(compilation).HOOK_NAME.tapAsync('YourPluginName', () => { ... });
  1456. */
  1457. // TODO remove me in the next major release in favor getCompilationHooks
  1458. HtmlWebpackPlugin.getHooks = HtmlWebpackPlugin.getCompilationHooks;
  1459. HtmlWebpackPlugin.createHtmlTagObject = createHtmlTagObject;
  1460. module.exports = HtmlWebpackPlugin;