index.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. 'use strict';
  2. // use Polyfill for util.promisify in node versions < v8
  3. const promisify = require('util.promisify');
  4. const vm = require('vm');
  5. const fs = require('fs');
  6. const _ = require('lodash');
  7. const path = require('path');
  8. const childCompiler = require('./lib/compiler.js');
  9. const prettyError = require('./lib/errors.js');
  10. const chunkSorter = require('./lib/chunksorter.js');
  11. const fsStatAsync = promisify(fs.stat);
  12. const fsReadFileAsync = promisify(fs.readFile);
  13. class HtmlWebpackPlugin {
  14. constructor (options) {
  15. // Default options
  16. this.options = _.extend({
  17. template: path.join(__dirname, 'default_index.ejs'),
  18. templateParameters: templateParametersGenerator,
  19. filename: 'index.html',
  20. hash: false,
  21. inject: true,
  22. compile: true,
  23. favicon: false,
  24. minify: false,
  25. cache: true,
  26. showErrors: true,
  27. chunks: 'all',
  28. excludeChunks: [],
  29. chunksSortMode: 'auto',
  30. meta: {},
  31. title: 'Webpack App',
  32. xhtml: false
  33. }, options);
  34. }
  35. apply (compiler) {
  36. const self = this;
  37. let isCompilationCached = false;
  38. let compilationPromise;
  39. this.options.template = this.getFullTemplatePath(this.options.template, compiler.context);
  40. // convert absolute filename into relative so that webpack can
  41. // generate it at correct location
  42. const filename = this.options.filename;
  43. if (path.resolve(filename) === path.normalize(filename)) {
  44. this.options.filename = path.relative(compiler.options.output.path, filename);
  45. }
  46. // setup hooks for webpack 4
  47. if (compiler.hooks) {
  48. compiler.hooks.compilation.tap('HtmlWebpackPluginHooks', compilation => {
  49. const SyncWaterfallHook = require('tapable').SyncWaterfallHook;
  50. const AsyncSeriesWaterfallHook = require('tapable').AsyncSeriesWaterfallHook;
  51. compilation.hooks.htmlWebpackPluginAlterChunks = new SyncWaterfallHook(['chunks', 'objectWithPluginRef']);
  52. compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration = new AsyncSeriesWaterfallHook(['pluginArgs']);
  53. compilation.hooks.htmlWebpackPluginBeforeHtmlProcessing = new AsyncSeriesWaterfallHook(['pluginArgs']);
  54. compilation.hooks.htmlWebpackPluginAlterAssetTags = new AsyncSeriesWaterfallHook(['pluginArgs']);
  55. compilation.hooks.htmlWebpackPluginAfterHtmlProcessing = new AsyncSeriesWaterfallHook(['pluginArgs']);
  56. compilation.hooks.htmlWebpackPluginAfterEmit = new AsyncSeriesWaterfallHook(['pluginArgs']);
  57. });
  58. }
  59. // Backwards compatible version of: compiler.hooks.make.tapAsync()
  60. (compiler.hooks ? compiler.hooks.make.tapAsync.bind(compiler.hooks.make, 'HtmlWebpackPlugin') : compiler.plugin.bind(compiler, 'make'))((compilation, callback) => {
  61. // Compile the template (queued)
  62. compilationPromise = childCompiler.compileTemplate(self.options.template, compiler.context, self.options.filename, compilation)
  63. .catch(err => {
  64. compilation.errors.push(prettyError(err, compiler.context).toString());
  65. return {
  66. content: self.options.showErrors ? prettyError(err, compiler.context).toJsonHtml() : 'ERROR',
  67. outputName: self.options.filename
  68. };
  69. })
  70. .then(compilationResult => {
  71. // If the compilation change didnt change the cache is valid
  72. isCompilationCached = compilationResult.hash && self.childCompilerHash === compilationResult.hash;
  73. self.childCompilerHash = compilationResult.hash;
  74. self.childCompilationOutputName = compilationResult.outputName;
  75. callback();
  76. return compilationResult.content;
  77. });
  78. });
  79. // Backwards compatible version of: compiler.plugin.emit.tapAsync()
  80. (compiler.hooks ? compiler.hooks.emit.tapAsync.bind(compiler.hooks.emit, 'HtmlWebpackPlugin') : compiler.plugin.bind(compiler, 'emit'))((compilation, callback) => {
  81. const applyPluginsAsyncWaterfall = self.applyPluginsAsyncWaterfall(compilation);
  82. // Get chunks info as json
  83. // Note: we're excluding stuff that we don't need to improve toJson serialization speed.
  84. const chunkOnlyConfig = {
  85. assets: false,
  86. cached: false,
  87. children: false,
  88. chunks: true,
  89. chunkModules: false,
  90. chunkOrigins: false,
  91. errorDetails: false,
  92. hash: false,
  93. modules: false,
  94. reasons: false,
  95. source: false,
  96. timings: false,
  97. version: false
  98. };
  99. const allChunks = compilation.getStats().toJson(chunkOnlyConfig).chunks;
  100. // Filter chunks (options.chunks and options.excludeCHunks)
  101. let chunks = self.filterChunks(allChunks, self.options.chunks, self.options.excludeChunks);
  102. // Sort chunks
  103. chunks = self.sortChunks(chunks, self.options.chunksSortMode, compilation);
  104. // Let plugins alter the chunks and the chunk sorting
  105. if (compilation.hooks) {
  106. chunks = compilation.hooks.htmlWebpackPluginAlterChunks.call(chunks, { plugin: self });
  107. } else {
  108. // Before Webpack 4
  109. chunks = compilation.applyPluginsWaterfall('html-webpack-plugin-alter-chunks', chunks, { plugin: self });
  110. }
  111. // Get assets
  112. const assets = self.htmlWebpackPluginAssets(compilation, chunks);
  113. // If this is a hot update compilation, move on!
  114. // This solves a problem where an `index.html` file is generated for hot-update js files
  115. // It only happens in Webpack 2, where hot updates are emitted separately before the full bundle
  116. if (self.isHotUpdateCompilation(assets)) {
  117. return callback();
  118. }
  119. // If the template and the assets did not change we don't have to emit the html
  120. const assetJson = JSON.stringify(self.getAssetFiles(assets));
  121. if (isCompilationCached && self.options.cache && assetJson === self.assetJson) {
  122. return callback();
  123. } else {
  124. self.assetJson = assetJson;
  125. }
  126. Promise.resolve()
  127. // Favicon
  128. .then(() => {
  129. if (self.options.favicon) {
  130. return self.addFileToAssets(self.options.favicon, compilation)
  131. .then(faviconBasename => {
  132. let publicPath = compilation.mainTemplate.getPublicPath({hash: compilation.hash}) || '';
  133. if (publicPath && publicPath.substr(-1) !== '/') {
  134. publicPath += '/';
  135. }
  136. assets.favicon = publicPath + faviconBasename;
  137. });
  138. }
  139. })
  140. // Wait for the compilation to finish
  141. .then(() => compilationPromise)
  142. .then(compiledTemplate => {
  143. // Allow to use a custom function / string instead
  144. if (self.options.templateContent !== undefined) {
  145. return self.options.templateContent;
  146. }
  147. // Once everything is compiled evaluate the html factory
  148. // and replace it with its content
  149. return self.evaluateCompilationResult(compilation, compiledTemplate);
  150. })
  151. // Allow plugins to make changes to the assets before invoking the template
  152. // This only makes sense to use if `inject` is `false`
  153. .then(compilationResult => applyPluginsAsyncWaterfall('html-webpack-plugin-before-html-generation', false, {
  154. assets: assets,
  155. outputName: self.childCompilationOutputName,
  156. plugin: self
  157. })
  158. .then(() => compilationResult))
  159. // Execute the template
  160. .then(compilationResult => typeof compilationResult !== 'function'
  161. ? compilationResult
  162. : self.executeTemplate(compilationResult, chunks, assets, compilation))
  163. // Allow plugins to change the html before assets are injected
  164. .then(html => {
  165. const pluginArgs = {html: html, assets: assets, plugin: self, outputName: self.childCompilationOutputName};
  166. return applyPluginsAsyncWaterfall('html-webpack-plugin-before-html-processing', true, pluginArgs);
  167. })
  168. .then(result => {
  169. const html = result.html;
  170. const assets = result.assets;
  171. // Prepare script and link tags
  172. const assetTags = self.generateHtmlTags(assets);
  173. const pluginArgs = {head: assetTags.head, body: assetTags.body, plugin: self, chunks: chunks, outputName: self.childCompilationOutputName};
  174. // Allow plugins to change the assetTag definitions
  175. return applyPluginsAsyncWaterfall('html-webpack-plugin-alter-asset-tags', true, pluginArgs)
  176. .then(result => self.postProcessHtml(html, assets, { body: result.body, head: result.head })
  177. .then(html => _.extend(result, {html: html, assets: assets})));
  178. })
  179. // Allow plugins to change the html after assets are injected
  180. .then(result => {
  181. const html = result.html;
  182. const assets = result.assets;
  183. const pluginArgs = {html: html, assets: assets, plugin: self, outputName: self.childCompilationOutputName};
  184. return applyPluginsAsyncWaterfall('html-webpack-plugin-after-html-processing', true, pluginArgs)
  185. .then(result => result.html);
  186. })
  187. .catch(err => {
  188. // In case anything went wrong the promise is resolved
  189. // with the error message and an error is logged
  190. compilation.errors.push(prettyError(err, compiler.context).toString());
  191. // Prevent caching
  192. self.hash = null;
  193. return self.options.showErrors ? prettyError(err, compiler.context).toHtml() : 'ERROR';
  194. })
  195. .then(html => {
  196. // Replace the compilation result with the evaluated html code
  197. compilation.assets[self.childCompilationOutputName] = {
  198. source: () => html,
  199. size: () => html.length
  200. };
  201. })
  202. .then(() => applyPluginsAsyncWaterfall('html-webpack-plugin-after-emit', false, {
  203. html: compilation.assets[self.childCompilationOutputName],
  204. outputName: self.childCompilationOutputName,
  205. plugin: self
  206. }).catch(err => {
  207. console.error(err);
  208. return null;
  209. }).then(() => null))
  210. // Let webpack continue with it
  211. .then(() => {
  212. callback();
  213. });
  214. });
  215. }
  216. /**
  217. * Evaluates the child compilation result
  218. * Returns a promise
  219. */
  220. evaluateCompilationResult (compilation, source) {
  221. if (!source) {
  222. return Promise.reject('The child compilation didn\'t provide a result');
  223. }
  224. // The LibraryTemplatePlugin stores the template result in a local variable.
  225. // To extract the result during the evaluation this part has to be removed.
  226. source = source.replace('var HTML_WEBPACK_PLUGIN_RESULT =', '');
  227. const template = this.options.template.replace(/^.+!/, '').replace(/\?.+$/, '');
  228. const vmContext = vm.createContext(_.extend({HTML_WEBPACK_PLUGIN: true, require: require}, global));
  229. const vmScript = new vm.Script(source, {filename: template});
  230. // Evaluate code and cast to string
  231. let newSource;
  232. try {
  233. newSource = vmScript.runInContext(vmContext);
  234. } catch (e) {
  235. return Promise.reject(e);
  236. }
  237. if (typeof newSource === 'object' && newSource.__esModule && newSource.default) {
  238. newSource = newSource.default;
  239. }
  240. return typeof newSource === 'string' || typeof newSource === 'function'
  241. ? Promise.resolve(newSource)
  242. : Promise.reject('The loader "' + this.options.template + '" didn\'t return html.');
  243. }
  244. /**
  245. * Generate the template parameters for the template function
  246. */
  247. getTemplateParameters (compilation, assets) {
  248. if (typeof this.options.templateParameters === 'function') {
  249. return this.options.templateParameters(compilation, assets, this.options);
  250. }
  251. if (typeof this.options.templateParameters === 'object') {
  252. return this.options.templateParameters;
  253. }
  254. return {};
  255. }
  256. /**
  257. * Html post processing
  258. *
  259. * Returns a promise
  260. */
  261. executeTemplate (templateFunction, chunks, assets, compilation) {
  262. return Promise.resolve()
  263. // Template processing
  264. .then(() => {
  265. const templateParams = this.getTemplateParameters(compilation, assets);
  266. let html = '';
  267. try {
  268. html = templateFunction(templateParams);
  269. } catch (e) {
  270. compilation.errors.push(new Error('Template execution failed: ' + e));
  271. return Promise.reject(e);
  272. }
  273. return html;
  274. });
  275. }
  276. /**
  277. * Html post processing
  278. *
  279. * Returns a promise
  280. */
  281. postProcessHtml (html, assets, assetTags) {
  282. const self = this;
  283. if (typeof html !== 'string') {
  284. return Promise.reject('Expected html to be a string but got ' + JSON.stringify(html));
  285. }
  286. return Promise.resolve()
  287. // Inject
  288. .then(() => {
  289. if (self.options.inject) {
  290. return self.injectAssetsIntoHtml(html, assets, assetTags);
  291. } else {
  292. return html;
  293. }
  294. })
  295. // Minify
  296. .then(html => {
  297. if (self.options.minify) {
  298. const minify = require('html-minifier').minify;
  299. return minify(html, self.options.minify);
  300. }
  301. return html;
  302. });
  303. }
  304. /*
  305. * Pushes the content of the given filename to the compilation assets
  306. */
  307. addFileToAssets (filename, compilation) {
  308. filename = path.resolve(compilation.compiler.context, filename);
  309. return Promise.all([
  310. fsStatAsync(filename),
  311. fsReadFileAsync(filename)
  312. ])
  313. .then(([size, source]) => {
  314. return {
  315. size,
  316. source
  317. };
  318. })
  319. .catch(() => Promise.reject(new Error('HtmlWebpackPlugin: could not load file ' + filename)))
  320. .then(results => {
  321. const basename = path.basename(filename);
  322. if (compilation.fileDependencies.add) {
  323. compilation.fileDependencies.add(filename);
  324. } else {
  325. // Before Webpack 4 - fileDepenencies was an array
  326. compilation.fileDependencies.push(filename);
  327. }
  328. compilation.assets[basename] = {
  329. source: () => results.source,
  330. size: () => results.size.size
  331. };
  332. return basename;
  333. });
  334. }
  335. /**
  336. * Helper to sort chunks
  337. */
  338. sortChunks (chunks, sortMode, compilation) {
  339. // Custom function
  340. if (typeof sortMode === 'function') {
  341. return chunks.sort(sortMode);
  342. }
  343. // Check if the given sort mode is a valid chunkSorter sort mode
  344. if (typeof chunkSorter[sortMode] !== 'undefined') {
  345. return chunkSorter[sortMode](chunks, this.options, compilation);
  346. }
  347. throw new Error('"' + sortMode + '" is not a valid chunk sort mode');
  348. }
  349. /**
  350. * Return all chunks from the compilation result which match the exclude and include filters
  351. */
  352. filterChunks (chunks, includedChunks, excludedChunks) {
  353. return chunks.filter(chunk => {
  354. const chunkName = chunk.names[0];
  355. // This chunk doesn't have a name. This script can't handled it.
  356. if (chunkName === undefined) {
  357. return false;
  358. }
  359. // Skip if the chunk should be lazy loaded
  360. if (typeof chunk.isInitial === 'function') {
  361. if (!chunk.isInitial()) {
  362. return false;
  363. }
  364. } else if (!chunk.initial) {
  365. return false;
  366. }
  367. // Skip if the chunks should be filtered and the given chunk was not added explicity
  368. if (Array.isArray(includedChunks) && includedChunks.indexOf(chunkName) === -1) {
  369. return false;
  370. }
  371. // Skip if the chunks should be filtered and the given chunk was excluded explicity
  372. if (Array.isArray(excludedChunks) && excludedChunks.indexOf(chunkName) !== -1) {
  373. return false;
  374. }
  375. // Add otherwise
  376. return true;
  377. });
  378. }
  379. isHotUpdateCompilation (assets) {
  380. return assets.js.length && assets.js.every(name => /\.hot-update\.js$/.test(name));
  381. }
  382. htmlWebpackPluginAssets (compilation, chunks) {
  383. const self = this;
  384. const compilationHash = compilation.hash;
  385. // Use the configured public path or build a relative path
  386. let publicPath = typeof compilation.options.output.publicPath !== 'undefined'
  387. // If a hard coded public path exists use it
  388. ? compilation.mainTemplate.getPublicPath({hash: compilationHash})
  389. // If no public path was set get a relative url path
  390. : path.relative(path.resolve(compilation.options.output.path, path.dirname(self.childCompilationOutputName)), compilation.options.output.path)
  391. .split(path.sep).join('/');
  392. if (publicPath.length && publicPath.substr(-1, 1) !== '/') {
  393. publicPath += '/';
  394. }
  395. const assets = {
  396. // The public path
  397. publicPath: publicPath,
  398. // Will contain all js & css files by chunk
  399. chunks: {},
  400. // Will contain all js files
  401. js: [],
  402. // Will contain all css files
  403. css: [],
  404. // Will contain the html5 appcache manifest files if it exists
  405. manifest: Object.keys(compilation.assets).filter(assetFile => path.extname(assetFile) === '.appcache')[0]
  406. };
  407. // Append a hash for cache busting
  408. if (this.options.hash) {
  409. assets.manifest = self.appendHash(assets.manifest, compilationHash);
  410. assets.favicon = self.appendHash(assets.favicon, compilationHash);
  411. }
  412. for (let i = 0; i < chunks.length; i++) {
  413. const chunk = chunks[i];
  414. const chunkName = chunk.names[0];
  415. assets.chunks[chunkName] = {};
  416. // Prepend the public path to all chunk files
  417. let chunkFiles = [].concat(chunk.files).map(chunkFile => publicPath + chunkFile);
  418. // Append a hash for cache busting
  419. if (this.options.hash) {
  420. chunkFiles = chunkFiles.map(chunkFile => self.appendHash(chunkFile, compilationHash));
  421. }
  422. // Webpack outputs an array for each chunk when using sourcemaps
  423. // or when one chunk hosts js and css simultaneously
  424. const js = chunkFiles.find(chunkFile => /.js($|\?)/.test(chunkFile));
  425. if (js) {
  426. assets.chunks[chunkName].size = chunk.size;
  427. assets.chunks[chunkName].entry = js;
  428. assets.chunks[chunkName].hash = chunk.hash;
  429. assets.js.push(js);
  430. }
  431. // Gather all css files
  432. const css = chunkFiles.filter(chunkFile => /.css($|\?)/.test(chunkFile));
  433. assets.chunks[chunkName].css = css;
  434. assets.css = assets.css.concat(css);
  435. }
  436. // Duplicate css assets can occur on occasion if more than one chunk
  437. // requires the same css.
  438. assets.css = _.uniq(assets.css);
  439. return assets;
  440. }
  441. /**
  442. * Generate meta tags
  443. */
  444. getMetaTags () {
  445. if (this.options.meta === false) {
  446. return [];
  447. }
  448. // Make tags self-closing in case of xhtml
  449. // Turn { "viewport" : "width=500, initial-scale=1" } into
  450. // [{ name:"viewport" content:"width=500, initial-scale=1" }]
  451. const selfClosingTag = !!this.options.xhtml;
  452. const metaTagAttributeObjects = Object.keys(this.options.meta).map((metaName) => {
  453. const metaTagContent = this.options.meta[metaName];
  454. return (typeof metaTagContent === 'object') ? metaTagContent : {
  455. name: metaName,
  456. content: metaTagContent
  457. };
  458. });
  459. // Turn [{ name:"viewport" content:"width=500, initial-scale=1" }] into
  460. // the html-webpack-plugin tag structure
  461. return metaTagAttributeObjects.map((metaTagAttributes) => {
  462. return {
  463. tagName: 'meta',
  464. voidTag: true,
  465. selfClosingTag: selfClosingTag,
  466. attributes: metaTagAttributes
  467. };
  468. });
  469. }
  470. /**
  471. * Injects the assets into the given html string
  472. */
  473. generateHtmlTags (assets) {
  474. // Turn script files into script tags
  475. const scripts = assets.js.map(scriptPath => ({
  476. tagName: 'script',
  477. closeTag: true,
  478. attributes: {
  479. type: 'text/javascript',
  480. src: scriptPath
  481. }
  482. }));
  483. // Make tags self-closing in case of xhtml
  484. const selfClosingTag = !!this.options.xhtml;
  485. // Turn css files into link tags
  486. const styles = assets.css.map(stylePath => ({
  487. tagName: 'link',
  488. selfClosingTag: selfClosingTag,
  489. voidTag: true,
  490. attributes: {
  491. href: stylePath,
  492. rel: 'stylesheet'
  493. }
  494. }));
  495. // Injection targets
  496. let head = this.getMetaTags();
  497. let body = [];
  498. // If there is a favicon present, add it to the head
  499. if (assets.favicon) {
  500. head.push({
  501. tagName: 'link',
  502. selfClosingTag: selfClosingTag,
  503. voidTag: true,
  504. attributes: {
  505. rel: 'shortcut icon',
  506. href: assets.favicon
  507. }
  508. });
  509. }
  510. // Add styles to the head
  511. head = head.concat(styles);
  512. // Add scripts to body or head
  513. if (this.options.inject === 'head') {
  514. head = head.concat(scripts);
  515. } else {
  516. body = body.concat(scripts);
  517. }
  518. return {head: head, body: body};
  519. }
  520. /**
  521. * Injects the assets into the given html string
  522. */
  523. injectAssetsIntoHtml (html, assets, assetTags) {
  524. const htmlRegExp = /(<html[^>]*>)/i;
  525. const headRegExp = /(<\/head\s*>)/i;
  526. const bodyRegExp = /(<\/body\s*>)/i;
  527. const body = assetTags.body.map(this.createHtmlTag.bind(this));
  528. const head = assetTags.head.map(this.createHtmlTag.bind(this));
  529. if (body.length) {
  530. if (bodyRegExp.test(html)) {
  531. // Append assets to body element
  532. html = html.replace(bodyRegExp, match => body.join('') + match);
  533. } else {
  534. // Append scripts to the end of the file if no <body> element exists:
  535. html += body.join('');
  536. }
  537. }
  538. if (head.length) {
  539. // Create a head tag if none exists
  540. if (!headRegExp.test(html)) {
  541. if (!htmlRegExp.test(html)) {
  542. html = '<head></head>' + html;
  543. } else {
  544. html = html.replace(htmlRegExp, match => match + '<head></head>');
  545. }
  546. }
  547. // Append assets to head element
  548. html = html.replace(headRegExp, match => head.join('') + match);
  549. }
  550. // Inject manifest into the opening html tag
  551. if (assets.manifest) {
  552. html = html.replace(/(<html[^>]*)(>)/i, (match, start, end) => {
  553. // Append the manifest only if no manifest was specified
  554. if (/\smanifest\s*=/.test(match)) {
  555. return match;
  556. }
  557. return start + ' manifest="' + assets.manifest + '"' + end;
  558. });
  559. }
  560. return html;
  561. }
  562. /**
  563. * Appends a cache busting hash
  564. */
  565. appendHash (url, hash) {
  566. if (!url) {
  567. return url;
  568. }
  569. return url + (url.indexOf('?') === -1 ? '?' : '&') + hash;
  570. }
  571. /**
  572. * Turn a tag definition into a html string
  573. */
  574. createHtmlTag (tagDefinition) {
  575. const attributes = Object.keys(tagDefinition.attributes || {})
  576. .filter(attributeName => tagDefinition.attributes[attributeName] !== false)
  577. .map(attributeName => {
  578. if (tagDefinition.attributes[attributeName] === true) {
  579. return attributeName;
  580. }
  581. return attributeName + '="' + tagDefinition.attributes[attributeName] + '"';
  582. });
  583. // Backport of 3.x void tag definition
  584. const voidTag = tagDefinition.voidTag !== undefined ? tagDefinition.voidTag : !tagDefinition.closeTag;
  585. const selfClosingTag = tagDefinition.voidTag !== undefined ? tagDefinition.voidTag && this.options.xhtml : tagDefinition.selfClosingTag;
  586. return '<' + [tagDefinition.tagName].concat(attributes).join(' ') + (selfClosingTag ? '/' : '') + '>' +
  587. (tagDefinition.innerHTML || '') +
  588. (voidTag ? '' : '</' + tagDefinition.tagName + '>');
  589. }
  590. /**
  591. * Helper to return the absolute template path with a fallback loader
  592. */
  593. getFullTemplatePath (template, context) {
  594. // If the template doesn't use a loader use the lodash template loader
  595. if (template.indexOf('!') === -1) {
  596. template = require.resolve('./lib/loader.js') + '!' + path.resolve(context, template);
  597. }
  598. // Resolve template path
  599. return template.replace(
  600. /([!])([^/\\][^!?]+|[^/\\!?])($|\?[^!?\n]+$)/,
  601. (match, prefix, filepath, postfix) => prefix + path.resolve(filepath) + postfix);
  602. }
  603. /**
  604. * Helper to return a sorted unique array of all asset files out of the
  605. * asset object
  606. */
  607. getAssetFiles (assets) {
  608. const files = _.uniq(Object.keys(assets).filter(assetType => assetType !== 'chunks' && assets[assetType]).reduce((files, assetType) => files.concat(assets[assetType]), []));
  609. files.sort();
  610. return files;
  611. }
  612. /**
  613. * Helper to promisify compilation.applyPluginsAsyncWaterfall that returns
  614. * a function that helps to merge given plugin arguments with processed ones
  615. */
  616. applyPluginsAsyncWaterfall (compilation) {
  617. if (compilation.hooks) {
  618. return (eventName, requiresResult, pluginArgs) => {
  619. const ccEventName = trainCaseToCamelCase(eventName);
  620. if (!compilation.hooks[ccEventName]) {
  621. compilation.errors.push(
  622. new Error('No hook found for ' + eventName)
  623. );
  624. }
  625. return compilation.hooks[ccEventName].promise(pluginArgs);
  626. };
  627. }
  628. // Before Webpack 4
  629. const promisedApplyPluginsAsyncWaterfall = function (name, init) {
  630. return new Promise((resolve, reject) => {
  631. const callback = function (err, result) {
  632. if (err) {
  633. return reject(err);
  634. }
  635. resolve(result);
  636. };
  637. compilation.applyPluginsAsyncWaterfall(name, init, callback);
  638. });
  639. };
  640. return (eventName, requiresResult, pluginArgs) => promisedApplyPluginsAsyncWaterfall(eventName, pluginArgs)
  641. .then(result => {
  642. if (requiresResult && !result) {
  643. compilation.warnings.push(
  644. new Error('Using ' + eventName + ' without returning a result is deprecated.')
  645. );
  646. }
  647. return _.extend(pluginArgs, result);
  648. });
  649. }
  650. }
  651. /**
  652. * Takes a string in train case and transforms it to camel case
  653. *
  654. * Example: 'hello-my-world' to 'helloMyWorld'
  655. *
  656. * @param {string} word
  657. */
  658. function trainCaseToCamelCase (word) {
  659. return word.replace(/-([\w])/g, (match, p1) => p1.toUpperCase());
  660. }
  661. /**
  662. * The default for options.templateParameter
  663. * Generate the template parameters
  664. */
  665. function templateParametersGenerator (compilation, assets, options) {
  666. return {
  667. compilation: compilation,
  668. webpack: compilation.getStats().toJson(),
  669. webpackConfig: compilation.options,
  670. htmlWebpackPlugin: {
  671. files: assets,
  672. options: options
  673. }
  674. };
  675. }
  676. module.exports = HtmlWebpackPlugin;