index.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  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' || options.scriptLoading === 'module', 'scriptLoading needs to be set to "defer", "blocking" or "module"');
  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 === 'defer',
  689. type: options.scriptLoading === 'module' ? 'module' : undefined,
  690. src: scriptAsset
  691. }
  692. }));
  693. }
  694. /**
  695. * Generate all style tags for the given file paths
  696. * @param {Array<string>} cssAssets
  697. * @returns {Array<HtmlTagObject>}
  698. */
  699. function generateStyleTags (cssAssets) {
  700. return cssAssets.map(styleAsset => ({
  701. tagName: 'link',
  702. voidTag: true,
  703. meta: { plugin: 'html-webpack-plugin' },
  704. attributes: {
  705. href: styleAsset,
  706. rel: 'stylesheet'
  707. }
  708. }));
  709. }
  710. /**
  711. * Generate an optional base tag
  712. * @param { false
  713. | string
  714. | {[attributeName: string]: string} // attributes e.g. { href:"http://example.com/page.html" target:"_blank" }
  715. } baseOption
  716. * @returns {Array<HtmlTagObject>}
  717. */
  718. function generateBaseTag (baseOption) {
  719. if (baseOption === false) {
  720. return [];
  721. } else {
  722. return [{
  723. tagName: 'base',
  724. voidTag: true,
  725. meta: { plugin: 'html-webpack-plugin' },
  726. attributes: (typeof baseOption === 'string') ? {
  727. href: baseOption
  728. } : baseOption
  729. }];
  730. }
  731. }
  732. /**
  733. * Generate all meta tags for the given meta configuration
  734. * @param {false | {
  735. [name: string]:
  736. false // disabled
  737. | string // name content pair e.g. {viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no'}`
  738. | {[attributeName: string]: string|boolean} // custom properties e.g. { name:"viewport" content:"width=500, initial-scale=1" }
  739. }} metaOptions
  740. * @returns {Array<HtmlTagObject>}
  741. */
  742. function generatedMetaTags (metaOptions) {
  743. if (metaOptions === false) {
  744. return [];
  745. }
  746. // Make tags self-closing in case of xhtml
  747. // Turn { "viewport" : "width=500, initial-scale=1" } into
  748. // [{ name:"viewport" content:"width=500, initial-scale=1" }]
  749. const metaTagAttributeObjects = Object.keys(metaOptions)
  750. .map((metaName) => {
  751. const metaTagContent = metaOptions[metaName];
  752. return (typeof metaTagContent === 'string') ? {
  753. name: metaName,
  754. content: metaTagContent
  755. } : metaTagContent;
  756. })
  757. .filter((attribute) => attribute !== false);
  758. // Turn [{ name:"viewport" content:"width=500, initial-scale=1" }] into
  759. // the html-webpack-plugin tag structure
  760. return metaTagAttributeObjects.map((metaTagAttributes) => {
  761. if (metaTagAttributes === false) {
  762. throw new Error('Invalid meta tag');
  763. }
  764. return {
  765. tagName: 'meta',
  766. voidTag: true,
  767. meta: { plugin: 'html-webpack-plugin' },
  768. attributes: metaTagAttributes
  769. };
  770. });
  771. }
  772. /**
  773. * Generate a favicon tag for the given file path
  774. * @param {string| undefined} faviconPath
  775. * @returns {Array<HtmlTagObject>}
  776. */
  777. function generateFaviconTags (faviconPath) {
  778. if (!faviconPath) {
  779. return [];
  780. }
  781. return [{
  782. tagName: 'link',
  783. voidTag: true,
  784. meta: { plugin: 'html-webpack-plugin' },
  785. attributes: {
  786. rel: 'icon',
  787. href: faviconPath
  788. }
  789. }];
  790. }
  791. /**
  792. * Group assets to head and bottom tags
  793. *
  794. * @param {{
  795. scripts: Array<HtmlTagObject>;
  796. styles: Array<HtmlTagObject>;
  797. meta: Array<HtmlTagObject>;
  798. }} assetTags
  799. * @param {"body" | "head"} scriptTarget
  800. * @returns {{
  801. headTags: Array<HtmlTagObject>;
  802. bodyTags: Array<HtmlTagObject>;
  803. }}
  804. */
  805. function generateAssetGroups (assetTags, scriptTarget) {
  806. /** @type {{ headTags: Array<HtmlTagObject>; bodyTags: Array<HtmlTagObject>; }} */
  807. const result = {
  808. headTags: [
  809. ...assetTags.meta,
  810. ...assetTags.styles
  811. ],
  812. bodyTags: []
  813. };
  814. // Add script tags to head or body depending on
  815. // the htmlPluginOptions
  816. if (scriptTarget === 'body') {
  817. result.bodyTags.push(...assetTags.scripts);
  818. } else {
  819. // If script loading is blocking add the scripts to the end of the head
  820. // If script loading is non-blocking add the scripts infront of the css files
  821. const insertPosition = options.scriptLoading === 'blocking' ? result.headTags.length : assetTags.meta.length;
  822. result.headTags.splice(insertPosition, 0, ...assetTags.scripts);
  823. }
  824. return result;
  825. }
  826. /**
  827. * Add toString methods for easier rendering
  828. * inside the template
  829. *
  830. * @param {Array<HtmlTagObject>} assetTagGroup
  831. * @returns {Array<HtmlTagObject>}
  832. */
  833. function prepareAssetTagGroupForRendering (assetTagGroup) {
  834. const xhtml = options.xhtml;
  835. return HtmlTagArray.from(assetTagGroup.map((assetTag) => {
  836. const copiedAssetTag = Object.assign({}, assetTag);
  837. copiedAssetTag.toString = function () {
  838. return htmlTagObjectToString(this, xhtml);
  839. };
  840. return copiedAssetTag;
  841. }));
  842. }
  843. /**
  844. * Injects the assets into the given html string
  845. *
  846. * @param {string} html
  847. * The input html
  848. * @param {any} assets
  849. * @param {{
  850. headTags: HtmlTagObject[],
  851. bodyTags: HtmlTagObject[]
  852. }} assetTags
  853. * The asset tags to inject
  854. *
  855. * @returns {string}
  856. */
  857. function injectAssetsIntoHtml (html, assets, assetTags) {
  858. const htmlRegExp = /(<html[^>]*>)/i;
  859. const headRegExp = /(<\/head\s*>)/i;
  860. const bodyRegExp = /(<\/body\s*>)/i;
  861. const body = assetTags.bodyTags.map((assetTagObject) => htmlTagObjectToString(assetTagObject, options.xhtml));
  862. const head = assetTags.headTags.map((assetTagObject) => htmlTagObjectToString(assetTagObject, options.xhtml));
  863. if (body.length) {
  864. if (bodyRegExp.test(html)) {
  865. // Append assets to body element
  866. html = html.replace(bodyRegExp, match => body.join('') + match);
  867. } else {
  868. // Append scripts to the end of the file if no <body> element exists:
  869. html += body.join('');
  870. }
  871. }
  872. if (head.length) {
  873. // Create a head tag if none exists
  874. if (!headRegExp.test(html)) {
  875. if (!htmlRegExp.test(html)) {
  876. html = '<head></head>' + html;
  877. } else {
  878. html = html.replace(htmlRegExp, match => match + '<head></head>');
  879. }
  880. }
  881. // Append assets to head element
  882. html = html.replace(headRegExp, match => head.join('') + match);
  883. }
  884. // Inject manifest into the opening html tag
  885. if (assets.manifest) {
  886. html = html.replace(/(<html[^>]*)(>)/i, (match, start, end) => {
  887. // Append the manifest only if no manifest was specified
  888. if (/\smanifest\s*=/.test(match)) {
  889. return match;
  890. }
  891. return start + ' manifest="' + assets.manifest + '"' + end;
  892. });
  893. }
  894. return html;
  895. }
  896. /**
  897. * Appends a cache busting hash to the query string of the url
  898. * E.g. http://localhost:8080/ -> http://localhost:8080/?50c9096ba6183fd728eeb065a26ec175
  899. * @param {string} url
  900. * @param {string} hash
  901. */
  902. function appendHash (url, hash) {
  903. if (!url) {
  904. return url;
  905. }
  906. return url + (url.indexOf('?') === -1 ? '?' : '&') + hash;
  907. }
  908. /**
  909. * Encode each path component using `encodeURIComponent` as files can contain characters
  910. * which needs special encoding in URLs like `+ `.
  911. *
  912. * Valid filesystem characters which need to be encoded for urls:
  913. *
  914. * # pound, % percent, & ampersand, { left curly bracket, } right curly bracket,
  915. * \ back slash, < left angle bracket, > right angle bracket, * asterisk, ? question mark,
  916. * blank spaces, $ dollar sign, ! exclamation point, ' single quotes, " double quotes,
  917. * : colon, @ at sign, + plus sign, ` backtick, | pipe, = equal sign
  918. *
  919. * However the query string must not be encoded:
  920. *
  921. * fo:demonstration-path/very fancy+name.js?path=/home?value=abc&value=def#zzz
  922. * ^ ^ ^ ^ ^ ^ ^ ^^ ^ ^ ^ ^ ^
  923. * | | | | | | | || | | | | |
  924. * encoded | | encoded | | || | | | | |
  925. * ignored ignored ignored ignored ignored
  926. *
  927. * @param {string} filePath
  928. */
  929. function urlencodePath (filePath) {
  930. // People use the filepath in quite unexpected ways.
  931. // Try to extract the first querystring of the url:
  932. //
  933. // some+path/demo.html?value=abc?def
  934. //
  935. const queryStringStart = filePath.indexOf('?');
  936. const urlPath = queryStringStart === -1 ? filePath : filePath.substr(0, queryStringStart);
  937. const queryString = filePath.substr(urlPath.length);
  938. // Encode all parts except '/' which are not part of the querystring:
  939. const encodedUrlPath = urlPath.split('/').map(encodeURIComponent).join('/');
  940. return encodedUrlPath + queryString;
  941. }
  942. /**
  943. * Helper to return the absolute template path with a fallback loader
  944. * @param {string} template
  945. * The path to the template e.g. './index.html'
  946. * @param {string} context
  947. * The webpack base resolution path for relative paths e.g. process.cwd()
  948. */
  949. function getFullTemplatePath (template, context) {
  950. if (template === 'auto') {
  951. template = path.resolve(context, 'src/index.ejs');
  952. if (!fs.existsSync(template)) {
  953. template = path.join(__dirname, 'default_index.ejs');
  954. }
  955. }
  956. // If the template doesn't use a loader use the lodash template loader
  957. if (template.indexOf('!') === -1) {
  958. template = require.resolve('./lib/loader.js') + '!' + path.resolve(context, template);
  959. }
  960. // Resolve template path
  961. return template.replace(
  962. /([!])([^/\\][^!?]+|[^/\\!?])($|\?[^!?\n]+$)/,
  963. (match, prefix, filepath, postfix) => prefix + path.resolve(filepath) + postfix);
  964. }
  965. /**
  966. * Minify the given string using html-minifier-terser
  967. *
  968. * As this is a breaking change to html-webpack-plugin 3.x
  969. * provide an extended error message to explain how to get back
  970. * to the old behaviour
  971. *
  972. * @param {string} html
  973. */
  974. function minifyHtml (html) {
  975. if (typeof options.minify !== 'object') {
  976. return html;
  977. }
  978. try {
  979. return require('html-minifier-terser').minify(html, options.minify);
  980. } catch (e) {
  981. const isParseError = String(e.message).indexOf('Parse Error') === 0;
  982. if (isParseError) {
  983. e.message = 'html-webpack-plugin could not minify the generated output.\n' +
  984. 'In production mode the html minifcation is enabled by default.\n' +
  985. 'If you are not generating a valid html output please disable it manually.\n' +
  986. 'You can do so by adding the following setting to your HtmlWebpackPlugin config:\n|\n|' +
  987. ' minify: false\n|\n' +
  988. 'See https://github.com/jantimon/html-webpack-plugin#options for details.\n\n' +
  989. 'For parser dedicated bugs please create an issue here:\n' +
  990. 'https://danielruf.github.io/html-minifier-terser/' +
  991. '\n' + e.message;
  992. }
  993. throw e;
  994. }
  995. }
  996. /**
  997. * Helper to return a sorted unique array of all asset files out of the
  998. * asset object
  999. */
  1000. function getAssetFiles (assets) {
  1001. const files = _.uniq(Object.keys(assets).filter(assetType => assetType !== 'chunks' && assets[assetType]).reduce((files, assetType) => files.concat(assets[assetType]), []));
  1002. files.sort();
  1003. return files;
  1004. }
  1005. }
  1006. /**
  1007. * The default for options.templateParameter
  1008. * Generate the template parameters
  1009. *
  1010. * Generate the template parameters for the template function
  1011. * @param {WebpackCompilation} compilation
  1012. * @param {{
  1013. publicPath: string,
  1014. js: Array<string>,
  1015. css: Array<string>,
  1016. manifest?: string,
  1017. favicon?: string
  1018. }} assets
  1019. * @param {{
  1020. headTags: HtmlTagObject[],
  1021. bodyTags: HtmlTagObject[]
  1022. }} assetTags
  1023. * @param {ProcessedHtmlWebpackOptions} options
  1024. * @returns {TemplateParameter}
  1025. */
  1026. function templateParametersGenerator (compilation, assets, assetTags, options) {
  1027. return {
  1028. compilation: compilation,
  1029. webpackConfig: compilation.options,
  1030. htmlWebpackPlugin: {
  1031. tags: assetTags,
  1032. files: assets,
  1033. options: options
  1034. }
  1035. };
  1036. }
  1037. // Statics:
  1038. /**
  1039. * The major version number of this plugin
  1040. */
  1041. HtmlWebpackPlugin.version = 5;
  1042. /**
  1043. * A static helper to get the hooks for this plugin
  1044. *
  1045. * Usage: HtmlWebpackPlugin.getHooks(compilation).HOOK_NAME.tapAsync('YourPluginName', () => { ... });
  1046. */
  1047. HtmlWebpackPlugin.getHooks = getHtmlWebpackPluginHooks;
  1048. HtmlWebpackPlugin.createHtmlTagObject = createHtmlTagObject;
  1049. module.exports = HtmlWebpackPlugin;