child-compiler.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // @ts-check
  2. /** @typedef {import("webpack/lib/Compilation.js")} WebpackCompilation */
  3. /** @typedef {import("webpack/lib/Compiler.js")} WebpackCompiler */
  4. /** @typedef {import("webpack/lib/Chunk.js")} WebpackChunk */
  5. 'use strict';
  6. /**
  7. * @file
  8. * This file uses webpack to compile a template with a child compiler.
  9. *
  10. * [TEMPLATE] -> [JAVASCRIPT]
  11. *
  12. */
  13. let instanceId = 0;
  14. /**
  15. * The HtmlWebpackChildCompiler is a helper to allow reusing one childCompiler
  16. * for multiple HtmlWebpackPlugin instances to improve the compilation performance.
  17. */
  18. class HtmlWebpackChildCompiler {
  19. /**
  20. *
  21. * @param {string[]} templates
  22. */
  23. constructor (templates) {
  24. /** Id for this ChildCompiler */
  25. this.id = instanceId++;
  26. /**
  27. * @type {string[]} templateIds
  28. * The template array will allow us to keep track which input generated which output
  29. */
  30. this.templates = templates;
  31. /**
  32. * @type {Promise<{[templatePath: string]: { content: string, hash: string, entry: WebpackChunk }}>}
  33. */
  34. this.compilationPromise; // eslint-disable-line
  35. /**
  36. * @type {number}
  37. */
  38. this.compilationStartedTimestamp; // eslint-disable-line
  39. /**
  40. * @type {number}
  41. */
  42. this.compilationEndedTimestamp; // eslint-disable-line
  43. /**
  44. * All file dependencies of the child compiler
  45. * @type {{fileDependencies: string[], contextDependencies: string[], missingDependencies: string[]}}
  46. */
  47. this.fileDependencies = { fileDependencies: [], contextDependencies: [], missingDependencies: [] };
  48. }
  49. /**
  50. * Returns true if the childCompiler is currently compiling
  51. * @returns {boolean}
  52. */
  53. isCompiling () {
  54. return !this.didCompile() && this.compilationStartedTimestamp !== undefined;
  55. }
  56. /**
  57. * Returns true if the childCompiler is done compiling
  58. */
  59. didCompile () {
  60. return this.compilationEndedTimestamp !== undefined;
  61. }
  62. /**
  63. * This function will start the template compilation
  64. * once it is started no more templates can be added
  65. *
  66. * @param {import('webpack').Compilation} mainCompilation
  67. * @returns {Promise<{[templatePath: string]: { content: string, hash: string, entry: WebpackChunk }}>}
  68. */
  69. compileTemplates (mainCompilation) {
  70. const webpack = mainCompilation.compiler.webpack;
  71. const Compilation = webpack.Compilation;
  72. const NodeTemplatePlugin = webpack.node.NodeTemplatePlugin;
  73. const NodeTargetPlugin = webpack.node.NodeTargetPlugin;
  74. const LoaderTargetPlugin = webpack.LoaderTargetPlugin;
  75. const EntryPlugin = webpack.EntryPlugin;
  76. // To prevent multiple compilations for the same template
  77. // the compilation is cached in a promise.
  78. // If it already exists return
  79. if (this.compilationPromise) {
  80. return this.compilationPromise;
  81. }
  82. const outputOptions = {
  83. filename: '__child-[name]',
  84. publicPath: '',
  85. library: {
  86. type: 'var',
  87. name: 'HTML_WEBPACK_PLUGIN_RESULT'
  88. },
  89. scriptType: /** @type {'text/javascript'} */('text/javascript'),
  90. iife: true
  91. };
  92. const compilerName = 'HtmlWebpackCompiler';
  93. // Create an additional child compiler which takes the template
  94. // and turns it into an Node.JS html factory.
  95. // This allows us to use loaders during the compilation
  96. const childCompiler = mainCompilation.createChildCompiler(compilerName, outputOptions, [
  97. // Compile the template to nodejs javascript
  98. new NodeTargetPlugin(),
  99. new NodeTemplatePlugin(),
  100. new LoaderTargetPlugin('node'),
  101. new webpack.library.EnableLibraryPlugin('var')
  102. ]);
  103. // The file path context which webpack uses to resolve all relative files to
  104. childCompiler.context = mainCompilation.compiler.context;
  105. // Generate output file names
  106. const temporaryTemplateNames = this.templates.map((template, index) => `__child-HtmlWebpackPlugin_${index}-${this.id}`);
  107. // Add all templates
  108. this.templates.forEach((template, index) => {
  109. new EntryPlugin(childCompiler.context, 'data:text/javascript,__webpack_public_path__ = __webpack_base_uri__ = htmlWebpackPluginPublicPath;', `HtmlWebpackPlugin_${index}-${this.id}`).apply(childCompiler);
  110. new EntryPlugin(childCompiler.context, template, `HtmlWebpackPlugin_${index}-${this.id}`).apply(childCompiler);
  111. });
  112. // The templates are compiled and executed by NodeJS - similar to server side rendering
  113. // Unfortunately this causes issues as some loaders require an absolute URL to support ES Modules
  114. // The following config enables relative URL support for the child compiler
  115. childCompiler.options.module = { ...childCompiler.options.module };
  116. childCompiler.options.module.parser = { ...childCompiler.options.module.parser };
  117. childCompiler.options.module.parser.javascript = { ...childCompiler.options.module.parser.javascript,
  118. url: 'relative' };
  119. this.compilationStartedTimestamp = new Date().getTime();
  120. this.compilationPromise = new Promise((resolve, reject) => {
  121. const extractedAssets = [];
  122. childCompiler.hooks.thisCompilation.tap('HtmlWebpackPlugin', (compilation) => {
  123. compilation.hooks.processAssets.tap(
  124. {
  125. name: 'HtmlWebpackPlugin',
  126. stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
  127. },
  128. (assets) => {
  129. temporaryTemplateNames.forEach((temporaryTemplateName) => {
  130. if (assets[temporaryTemplateName]) {
  131. extractedAssets.push(assets[temporaryTemplateName]);
  132. compilation.deleteAsset(temporaryTemplateName);
  133. }
  134. });
  135. }
  136. );
  137. });
  138. childCompiler.runAsChild((err, entries, childCompilation) => {
  139. // Extract templates
  140. const compiledTemplates = entries
  141. ? extractedAssets.map((asset) => asset.source())
  142. : [];
  143. // Extract file dependencies
  144. if (entries && childCompilation) {
  145. this.fileDependencies = { fileDependencies: Array.from(childCompilation.fileDependencies), contextDependencies: Array.from(childCompilation.contextDependencies), missingDependencies: Array.from(childCompilation.missingDependencies) };
  146. }
  147. // Reject the promise if the childCompilation contains error
  148. if (childCompilation && childCompilation.errors && childCompilation.errors.length) {
  149. const errorDetails = childCompilation.errors.map(error => {
  150. let message = error.message;
  151. if (error.stack) {
  152. message += '\n' + error.stack;
  153. }
  154. return message;
  155. }).join('\n');
  156. reject(new Error('Child compilation failed:\n' + errorDetails));
  157. return;
  158. }
  159. // Reject if the error object contains errors
  160. if (err) {
  161. reject(err);
  162. return;
  163. }
  164. if (!childCompilation || !entries) {
  165. reject(new Error('Empty child compilation'));
  166. return;
  167. }
  168. /**
  169. * @type {{[templatePath: string]: { content: string, hash: string, entry: WebpackChunk }}}
  170. */
  171. const result = {};
  172. compiledTemplates.forEach((templateSource, entryIndex) => {
  173. // The compiledTemplates are generated from the entries added in
  174. // the addTemplate function.
  175. // Therefore the array index of this.templates should be the as entryIndex.
  176. result[this.templates[entryIndex]] = {
  177. content: templateSource,
  178. hash: childCompilation.hash || 'XXXX',
  179. entry: entries[entryIndex]
  180. };
  181. });
  182. this.compilationEndedTimestamp = new Date().getTime();
  183. resolve(result);
  184. });
  185. });
  186. return this.compilationPromise;
  187. }
  188. }
  189. module.exports = {
  190. HtmlWebpackChildCompiler
  191. };