compiler.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. childCompiler.hooks.compilation.tap('HtmlWebpackPlugin', compilation => {
  59. if (compilation.cache) {
  60. if (!compilation.cache[compilerName]) {
  61. compilation.cache[compilerName] = {};
  62. }
  63. compilation.cache = compilation.cache[compilerName];
  64. }
  65. });
  66. // Compile and return a promise
  67. return new Promise((resolve, reject) => {
  68. childCompiler.runAsChild((err, entries, childCompilation) => {
  69. // Resolve / reject the promise
  70. if (childCompilation && childCompilation.errors && childCompilation.errors.length) {
  71. const errorDetails = childCompilation.errors.map(error => error.message + (error.error ? ':\n' + error.error : '')).join('\n');
  72. reject(new Error('Child compilation failed:\n' + errorDetails));
  73. } else if (err) {
  74. reject(err);
  75. } else {
  76. // Replace [hash] placeholders in filename
  77. const outputName = compilation.mainTemplate.hooks.assetPath.call(outputOptions.filename, {
  78. hash: childCompilation.hash,
  79. chunk: entries[0]
  80. });
  81. // Restore the parent compilation to the state like it
  82. // was before the child compilation
  83. compilation.assets[outputName] = assetsBeforeCompilation[outputName];
  84. if (assetsBeforeCompilation[outputName] === undefined) {
  85. // If it wasn't there - delete it
  86. delete compilation.assets[outputName];
  87. }
  88. resolve({
  89. // Hash of the template entry point
  90. hash: entries[0].hash,
  91. // Output name
  92. outputName: outputName,
  93. // Compiled code
  94. content: childCompilation.assets[outputName].source()
  95. });
  96. }
  97. });
  98. });
  99. };
  100. /**
  101. * Returns the child compiler name e.g. 'html-webpack-plugin for "index.html"'
  102. */
  103. function getCompilerName (context, filename) {
  104. const absolutePath = path.resolve(context, filename);
  105. const relativePath = path.relative(context, absolutePath);
  106. return 'html-webpack-plugin for "' + (absolutePath.length < relativePath.length ? absolutePath : relativePath) + '"';
  107. }