compiler.js 4.4 KB

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