index.js 39 KB

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