index.js 41 KB

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