compiler.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. /*
  2. * This file uses webpack to compile a template with a child compiler.
  3. *
  4. * [TEMPLATE] -> [JAVASCRIPT]
  5. *
  6. */
  7. 'use strict';
  8. const path = require('path');
  9. const NodeTemplatePlugin = require('webpack/lib/node/NodeTemplatePlugin');
  10. const NodeTargetPlugin = require('webpack/lib/node/NodeTargetPlugin');
  11. const LoaderTargetPlugin = require('webpack/lib/LoaderTargetPlugin');
  12. const LibraryTemplatePlugin = require('webpack/lib/LibraryTemplatePlugin');
  13. const SingleEntryPlugin = require('webpack/lib/SingleEntryPlugin');
  14. /**
  15. * Compiles the template into a nodejs factory, adds its to the compilation.assets
  16. * and returns a promise of the result asset object.
  17. *
  18. * @param template relative path to the template file
  19. * @param context path context
  20. * @param outputFilename the file name
  21. * @param compilation The webpack compilation object
  22. *
  23. * Returns an object:
  24. * {
  25. * hash: {String} - Base64 hash of the file
  26. * content: {String} - Javascript executable code of the template
  27. * }
  28. *
  29. */
  30. module.exports.compileTemplate = function compileTemplate (template, context, outputFilename, compilation) {
  31. // The entry file is just an empty helper as the dynamic template
  32. // require is added in "loader.js"
  33. const outputOptions = {
  34. filename: outputFilename,
  35. publicPath: compilation.outputOptions.publicPath
  36. };
  37. // Store the result of the parent compilation before we start the child compilation
  38. const assetsBeforeCompilation = Object.assign({}, compilation.assets[outputOptions.filename]);
  39. // Create an additional child compiler which takes the template
  40. // and turns it into an Node.JS html factory.
  41. // This allows us to use loaders during the compilation
  42. const compilerName = getCompilerName(context, outputFilename);
  43. const childCompiler = compilation.createChildCompiler(compilerName, outputOptions);
  44. childCompiler.context = context;
  45. new NodeTemplatePlugin(outputOptions).apply(childCompiler);
  46. new NodeTargetPlugin().apply(childCompiler);
  47. new LibraryTemplatePlugin('HTML_WEBPACK_PLUGIN_RESULT', 'var').apply(childCompiler);
  48. // Using undefined as name for the SingleEntryPlugin causes a unexpected output as described in
  49. // https://github.com/jantimon/html-webpack-plugin/issues/895
  50. // Using a string as a name for the SingleEntryPlugin causes problems with HMR as described in
  51. // https://github.com/jantimon/html-webpack-plugin/issues/900
  52. // Until the HMR issue is fixed we keep the ugly output:
  53. new SingleEntryPlugin(this.context, template, undefined).apply(childCompiler);
  54. new LoaderTargetPlugin('node').apply(childCompiler);
  55. // Fix for "Uncaught TypeError: __webpack_require__(...) is not a function"
  56. // Hot module replacement requires that every child compiler has its own
  57. // cache. @see https://github.com/ampedandwired/html-webpack-plugin/pull/179
  58. // Backwards compatible version of: childCompiler.hooks.compilation
  59. (childCompiler.hooks ? childCompiler.hooks.compilation.tap.bind(childCompiler.hooks.compilation, 'HtmlWebpackPlugin') : childCompiler.plugin.bind(childCompiler, 'compilation'))(compilation => {
  60. if (compilation.cache) {
  61. if (!compilation.cache[compilerName]) {
  62. compilation.cache[compilerName] = {};
  63. }
  64. compilation.cache = compilation.cache[compilerName];
  65. }
  66. });
  67. // Compile and return a promise
  68. return new Promise((resolve, reject) => {
  69. childCompiler.runAsChild((err, entries, childCompilation) => {
  70. // Resolve / reject the promise
  71. if (childCompilation && childCompilation.errors && childCompilation.errors.length) {
  72. const errorDetails = childCompilation.errors.map(error => error.message + (error.error ? ':\n' + error.error : '')).join('\n');
  73. reject(new Error('Child compilation failed:\n' + errorDetails));
  74. } else if (err) {
  75. reject(err);
  76. } else {
  77. // Replace [hash] placeholders in filename
  78. // In webpack 4 the plugin interface changed, so check for available fns
  79. const outputName = compilation.mainTemplate.getAssetPath
  80. ? compilation.mainTemplate.hooks.assetPath.call(outputOptions.filename, {
  81. hash: childCompilation.hash,
  82. chunk: entries[0]
  83. })
  84. : compilation.mainTemplate.applyPluginsWaterfall(
  85. 'asset-path',
  86. outputOptions.filename,
  87. {
  88. hash: childCompilation.hash,
  89. chunk: entries[0]
  90. });
  91. // Restore the parent compilation to the state like it
  92. // was before the child compilation
  93. compilation.assets[outputName] = assetsBeforeCompilation[outputName];
  94. if (assetsBeforeCompilation[outputName] === undefined) {
  95. // If it wasn't there - delete it
  96. delete compilation.assets[outputName];
  97. }
  98. resolve({
  99. // Hash of the template entry point
  100. hash: entries[0].hash,
  101. // Output name
  102. outputName: outputName,
  103. // Compiled code
  104. content: childCompilation.assets[outputName].source()
  105. });
  106. }
  107. });
  108. });
  109. };
  110. /**
  111. * Returns the child compiler name e.g. 'html-webpack-plugin for "index.html"'
  112. */
  113. function getCompilerName (context, filename) {
  114. const absolutePath = path.resolve(context, filename);
  115. const relativePath = path.relative(context, absolutePath);
  116. return 'html-webpack-plugin for "' + (absolutePath.length < relativePath.length ? absolutePath : relativePath) + '"';
  117. }