index.js 39 KB

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