index.js 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598
  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. new Error(
  1196. prettyError(templateResult.error, compiler.context).toString(),
  1197. ),
  1198. );
  1199. }
  1200. // If the child compilation was not executed during a previous main compile run
  1201. // it is a cached result
  1202. const isCompilationCached =
  1203. templateResult.mainCompilationHash !== compilation.hash;
  1204. /** Generated file paths from the entry point names */
  1205. const assetsInformationByGroups = this.getAssetsInformationByGroups(
  1206. compilation,
  1207. outputName,
  1208. sortedEntryNames,
  1209. );
  1210. // If the template and the assets did not change we don't have to emit the html
  1211. const newAssetJson = JSON.stringify(
  1212. this.getAssetFiles(assetsInformationByGroups),
  1213. );
  1214. if (
  1215. isCompilationCached &&
  1216. this.options.cache &&
  1217. assetJson.value === newAssetJson
  1218. ) {
  1219. previousEmittedAssets.forEach(({ name, source, info }) => {
  1220. compilation.emitAsset(name, source, info);
  1221. });
  1222. return callback();
  1223. } else {
  1224. previousEmittedAssets.length = 0;
  1225. assetJson.value = newAssetJson;
  1226. }
  1227. // The html-webpack plugin uses a object representation for the html-tags which will be injected
  1228. // to allow altering them more easily
  1229. // Just before they are converted a third-party-plugin author might change the order and content
  1230. const assetsPromise = this.generateFavicon(
  1231. compiler,
  1232. this.options.favicon,
  1233. compilation,
  1234. assetsInformationByGroups.publicPath,
  1235. previousEmittedAssets,
  1236. ).then((faviconPath) => {
  1237. assetsInformationByGroups.favicon = faviconPath;
  1238. return HtmlWebpackPlugin.getCompilationHooks(
  1239. compilation,
  1240. ).beforeAssetTagGeneration.promise({
  1241. assets: assetsInformationByGroups,
  1242. outputName,
  1243. plugin: this,
  1244. });
  1245. });
  1246. // Turn the js and css paths into grouped HtmlTagObjects
  1247. const assetTagGroupsPromise = assetsPromise
  1248. // And allow third-party-plugin authors to reorder and change the assetTags before they are grouped
  1249. .then(({ assets }) =>
  1250. HtmlWebpackPlugin.getCompilationHooks(
  1251. compilation,
  1252. ).alterAssetTags.promise({
  1253. assetTags: {
  1254. scripts: this.generatedScriptTags(assets.js),
  1255. styles: this.generateStyleTags(assets.css),
  1256. meta: [
  1257. ...(this.options.base !== false
  1258. ? this.generateBaseTag(this.options.base)
  1259. : []),
  1260. ...this.generatedMetaTags(this.options.meta),
  1261. ...(assets.favicon
  1262. ? this.generateFaviconTag(assets.favicon)
  1263. : []),
  1264. ],
  1265. },
  1266. outputName,
  1267. publicPath: assetsInformationByGroups.publicPath,
  1268. plugin: this,
  1269. }),
  1270. )
  1271. .then(({ assetTags }) => {
  1272. // Inject scripts to body unless it set explicitly to head
  1273. const scriptTarget =
  1274. this.options.inject === "head" ||
  1275. (this.options.inject !== "body" &&
  1276. this.options.scriptLoading !== "blocking")
  1277. ? "head"
  1278. : "body";
  1279. // Group assets to `head` and `body` tag arrays
  1280. const assetGroups = this.groupAssetsByElements(assetTags, scriptTarget);
  1281. // Allow third-party-plugin authors to reorder and change the assetTags once they are grouped
  1282. return HtmlWebpackPlugin.getCompilationHooks(
  1283. compilation,
  1284. ).alterAssetTagGroups.promise({
  1285. headTags: assetGroups.headTags,
  1286. bodyTags: assetGroups.bodyTags,
  1287. outputName,
  1288. publicPath: assetsInformationByGroups.publicPath,
  1289. plugin: this,
  1290. });
  1291. });
  1292. // Turn the compiled template into a nodejs function or into a nodejs string
  1293. const templateEvaluationPromise = Promise.resolve().then(() => {
  1294. if ("error" in templateResult) {
  1295. return this.options.showErrors
  1296. ? prettyError(templateResult.error, compiler.context).toHtml()
  1297. : "ERROR";
  1298. }
  1299. // Allow to use a custom function / string instead
  1300. if (this.options.templateContent !== false) {
  1301. return this.options.templateContent;
  1302. }
  1303. // Once everything is compiled evaluate the html factory and replace it with its content
  1304. if ("compiledEntry" in templateResult) {
  1305. const compiledEntry = templateResult.compiledEntry;
  1306. const assets = compiledEntry.assets;
  1307. // Store assets from child compiler to re-emit them later
  1308. for (const name in assets) {
  1309. previousEmittedAssets.push({
  1310. name,
  1311. source: assets[name].source,
  1312. info: assets[name].info,
  1313. });
  1314. }
  1315. return this.evaluateCompilationResult(
  1316. compiledEntry.content,
  1317. assetsInformationByGroups.publicPath,
  1318. this.options.template,
  1319. );
  1320. }
  1321. return Promise.reject(
  1322. new Error("Child compilation contained no compiledEntry"),
  1323. );
  1324. });
  1325. const templateExecutionPromise = Promise.all([
  1326. assetsPromise,
  1327. assetTagGroupsPromise,
  1328. templateEvaluationPromise,
  1329. ])
  1330. // Execute the template
  1331. .then(([assetsHookResult, assetTags, compilationResult]) =>
  1332. typeof compilationResult !== "function"
  1333. ? compilationResult
  1334. : this.executeTemplate(
  1335. compilationResult,
  1336. assetsHookResult.assets,
  1337. { headTags: assetTags.headTags, bodyTags: assetTags.bodyTags },
  1338. compilation,
  1339. ),
  1340. );
  1341. const injectedHtmlPromise = Promise.all([
  1342. assetTagGroupsPromise,
  1343. templateExecutionPromise,
  1344. ])
  1345. // Allow plugins to change the html before assets are injected
  1346. .then(([assetTags, html]) => {
  1347. const pluginArgs = {
  1348. html,
  1349. headTags: assetTags.headTags,
  1350. bodyTags: assetTags.bodyTags,
  1351. plugin: this,
  1352. outputName,
  1353. };
  1354. return HtmlWebpackPlugin.getCompilationHooks(
  1355. compilation,
  1356. ).afterTemplateExecution.promise(pluginArgs);
  1357. })
  1358. .then(({ html, headTags, bodyTags }) => {
  1359. return this.postProcessHtml(compiler, html, assetsInformationByGroups, {
  1360. headTags,
  1361. bodyTags,
  1362. });
  1363. });
  1364. const emitHtmlPromise = injectedHtmlPromise
  1365. // Allow plugins to change the html after assets are injected
  1366. .then((html) => {
  1367. const pluginArgs = { html, plugin: this, outputName };
  1368. return HtmlWebpackPlugin.getCompilationHooks(compilation)
  1369. .beforeEmit.promise(pluginArgs)
  1370. .then((result) => result.html);
  1371. })
  1372. .catch((err) => {
  1373. // In case anything went wrong the promise is resolved
  1374. // with the error message and an error is logged
  1375. compilation.errors.push(
  1376. new Error(prettyError(err, compiler.context).toString()),
  1377. );
  1378. return this.options.showErrors
  1379. ? prettyError(err, compiler.context).toHtml()
  1380. : "ERROR";
  1381. })
  1382. .then((html) => {
  1383. const filename = outputName.replace(
  1384. /\[templatehash([^\]]*)\]/g,
  1385. require("util").deprecate(
  1386. (match, options) => `[contenthash${options}]`,
  1387. "[templatehash] is now [contenthash]",
  1388. ),
  1389. );
  1390. const replacedFilename = this.replacePlaceholdersInFilename(
  1391. compiler,
  1392. filename,
  1393. html,
  1394. compilation,
  1395. );
  1396. const source = new compiler.webpack.sources.RawSource(html, false);
  1397. // Add the evaluated html code to the webpack assets
  1398. compilation.emitAsset(
  1399. replacedFilename.path,
  1400. source,
  1401. replacedFilename.info,
  1402. );
  1403. previousEmittedAssets.push({ name: replacedFilename.path, source });
  1404. return replacedFilename.path;
  1405. })
  1406. .then((finalOutputName) =>
  1407. HtmlWebpackPlugin.getCompilationHooks(compilation)
  1408. .afterEmit.promise({
  1409. outputName: finalOutputName,
  1410. plugin: this,
  1411. })
  1412. .catch((err) => {
  1413. /** @type {Logger} */
  1414. (this.logger).error(err);
  1415. return null;
  1416. })
  1417. .then(() => null),
  1418. );
  1419. // Once all files are added to the webpack compilation
  1420. // let the webpack compiler continue
  1421. emitHtmlPromise.then(() => {
  1422. callback();
  1423. });
  1424. }
  1425. }
  1426. /**
  1427. * The default for options.templateParameter
  1428. * Generate the template parameters
  1429. *
  1430. * Generate the template parameters for the template function
  1431. * @param {Compilation} compilation
  1432. * @param {AssetsInformationByGroups} assets
  1433. * @param {{
  1434. headTags: HtmlTagObject[],
  1435. bodyTags: HtmlTagObject[]
  1436. }} assetTags
  1437. * @param {ProcessedHtmlWebpackOptions} options
  1438. * @returns {TemplateParameter}
  1439. */
  1440. function templateParametersGenerator(compilation, assets, assetTags, options) {
  1441. return {
  1442. compilation: compilation,
  1443. webpackConfig: compilation.options,
  1444. htmlWebpackPlugin: {
  1445. tags: assetTags,
  1446. files: assets,
  1447. options: options,
  1448. },
  1449. };
  1450. }
  1451. // Statics:
  1452. /**
  1453. * The major version number of this plugin
  1454. */
  1455. HtmlWebpackPlugin.version = 5;
  1456. /**
  1457. * A static helper to get the hooks for this plugin
  1458. *
  1459. * Usage: HtmlWebpackPlugin.getHooks(compilation).HOOK_NAME.tapAsync('YourPluginName', () => { ... });
  1460. */
  1461. // TODO remove me in the next major release in favor getCompilationHooks
  1462. HtmlWebpackPlugin.getHooks = HtmlWebpackPlugin.getCompilationHooks;
  1463. HtmlWebpackPlugin.createHtmlTagObject = createHtmlTagObject;
  1464. module.exports = HtmlWebpackPlugin;