HotModuleReplacementPlugin.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. var Template = require("./Template");
  7. var ModuleHotAcceptDependency = require("./dependencies/ModuleHotAcceptDependency");
  8. var ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency");
  9. var RawSource = require("webpack-sources").RawSource;
  10. var ConstDependency = require("./dependencies/ConstDependency");
  11. var NullFactory = require("./NullFactory");
  12. const ParserHelpers = require("./ParserHelpers");
  13. function HotModuleReplacementPlugin(options) {
  14. options = options || {};
  15. this.multiStep = options.multiStep;
  16. this.fullBuildTimeout = options.fullBuildTimeout || 200;
  17. }
  18. module.exports = HotModuleReplacementPlugin;
  19. HotModuleReplacementPlugin.prototype.apply = function(compiler) {
  20. var multiStep = this.multiStep;
  21. var fullBuildTimeout = this.fullBuildTimeout;
  22. var hotUpdateChunkFilename = compiler.options.output.hotUpdateChunkFilename;
  23. var hotUpdateMainFilename = compiler.options.output.hotUpdateMainFilename;
  24. compiler.plugin("compilation", function(compilation, params) {
  25. var hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate;
  26. if(!hotUpdateChunkTemplate) return;
  27. var normalModuleFactory = params.normalModuleFactory;
  28. compilation.dependencyFactories.set(ConstDependency, new NullFactory());
  29. compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
  30. compilation.dependencyFactories.set(ModuleHotAcceptDependency, normalModuleFactory);
  31. compilation.dependencyTemplates.set(ModuleHotAcceptDependency, new ModuleHotAcceptDependency.Template());
  32. compilation.dependencyFactories.set(ModuleHotDeclineDependency, normalModuleFactory);
  33. compilation.dependencyTemplates.set(ModuleHotDeclineDependency, new ModuleHotDeclineDependency.Template());
  34. compilation.plugin("record", function(compilation, records) {
  35. if(records.hash === this.hash) return;
  36. records.hash = compilation.hash;
  37. records.moduleHashs = {};
  38. this.modules.forEach(function(module) {
  39. var identifier = module.identifier();
  40. var hash = require("crypto").createHash("md5");
  41. module.updateHash(hash);
  42. records.moduleHashs[identifier] = hash.digest("hex");
  43. });
  44. records.chunkHashs = {};
  45. this.chunks.forEach(function(chunk) {
  46. records.chunkHashs[chunk.id] = chunk.hash;
  47. });
  48. records.chunkModuleIds = {};
  49. this.chunks.forEach(function(chunk) {
  50. records.chunkModuleIds[chunk.id] = chunk.modules.map(function(m) {
  51. return m.id;
  52. });
  53. });
  54. });
  55. var initialPass = false;
  56. var recompilation = false;
  57. compilation.plugin("after-hash", function() {
  58. var records = this.records;
  59. if(!records) {
  60. initialPass = true;
  61. return;
  62. }
  63. if(!records.hash)
  64. initialPass = true;
  65. var preHash = records.preHash || "x";
  66. var prepreHash = records.prepreHash || "x";
  67. if(preHash === this.hash) {
  68. recompilation = true;
  69. this.modifyHash(prepreHash);
  70. return;
  71. }
  72. records.prepreHash = records.hash || "x";
  73. records.preHash = this.hash;
  74. this.modifyHash(records.prepreHash);
  75. });
  76. compilation.plugin("should-generate-chunk-assets", function() {
  77. if(multiStep && !recompilation && !initialPass)
  78. return false;
  79. });
  80. compilation.plugin("need-additional-pass", function() {
  81. if(multiStep && !recompilation && !initialPass)
  82. return true;
  83. });
  84. compiler.plugin("additional-pass", function(callback) {
  85. if(multiStep)
  86. return setTimeout(callback, fullBuildTimeout);
  87. return callback();
  88. });
  89. compilation.plugin("additional-chunk-assets", function() {
  90. var records = this.records;
  91. if(records.hash === this.hash) return;
  92. if(!records.moduleHashs || !records.chunkHashs || !records.chunkModuleIds) return;
  93. this.modules.forEach(function(module) {
  94. var identifier = module.identifier();
  95. var hash = require("crypto").createHash("md5");
  96. module.updateHash(hash);
  97. hash = hash.digest("hex");
  98. module.hotUpdate = records.moduleHashs[identifier] !== hash;
  99. });
  100. var hotUpdateMainContent = {
  101. h: this.hash,
  102. c: {}
  103. };
  104. Object.keys(records.chunkHashs).forEach(function(chunkId) {
  105. chunkId = isNaN(+chunkId) ? chunkId : +chunkId;
  106. var currentChunk = this.chunks.find(chunk => chunk.id === chunkId);
  107. if(currentChunk) {
  108. var newModules = currentChunk.modules.filter(function(module) {
  109. return module.hotUpdate;
  110. });
  111. var allModules = {};
  112. currentChunk.modules.forEach(function(module) {
  113. allModules[module.id] = true;
  114. });
  115. var removedModules = records.chunkModuleIds[chunkId].filter(function(id) {
  116. return !allModules[id];
  117. });
  118. if(newModules.length > 0 || removedModules.length > 0) {
  119. var source = hotUpdateChunkTemplate.render(chunkId, newModules, removedModules, this.hash, this.moduleTemplate, this.dependencyTemplates);
  120. var filename = this.getPath(hotUpdateChunkFilename, {
  121. hash: records.hash,
  122. chunk: currentChunk
  123. });
  124. this.additionalChunkAssets.push(filename);
  125. this.assets[filename] = source;
  126. hotUpdateMainContent.c[chunkId] = true;
  127. currentChunk.files.push(filename);
  128. this.applyPlugins("chunk-asset", currentChunk, filename);
  129. }
  130. } else {
  131. hotUpdateMainContent.c[chunkId] = false;
  132. }
  133. }, this);
  134. var source = new RawSource(JSON.stringify(hotUpdateMainContent));
  135. var filename = this.getPath(hotUpdateMainFilename, {
  136. hash: records.hash
  137. });
  138. this.assets[filename] = source;
  139. });
  140. compilation.mainTemplate.plugin("hash", function(hash) {
  141. hash.update("HotMainTemplateDecorator");
  142. });
  143. compilation.mainTemplate.plugin("module-require", function(_, chunk, hash, varModuleId) {
  144. return "hotCreateRequire(" + varModuleId + ")";
  145. });
  146. compilation.mainTemplate.plugin("require-extensions", function(source) {
  147. var buf = [source];
  148. buf.push("");
  149. buf.push("// __webpack_hash__");
  150. buf.push(this.requireFn + ".h = function() { return hotCurrentHash; };");
  151. return this.asString(buf);
  152. });
  153. compilation.mainTemplate.plugin("bootstrap", function(source, chunk, hash) {
  154. source = this.applyPluginsWaterfall("hot-bootstrap", source, chunk, hash);
  155. return this.asString([
  156. source,
  157. "",
  158. hotInitCode
  159. .replace(/\$require\$/g, this.requireFn)
  160. .replace(/\$hash\$/g, JSON.stringify(hash))
  161. .replace(/\/\*foreachInstalledChunks\*\//g, chunk.chunks.length > 0 ? "for(var chunkId in installedChunks)" : "var chunkId = " + JSON.stringify(chunk.id) + ";")
  162. ]);
  163. });
  164. compilation.mainTemplate.plugin("global-hash", function() {
  165. return true;
  166. });
  167. compilation.mainTemplate.plugin("current-hash", function(_, length) {
  168. if(isFinite(length))
  169. return "hotCurrentHash.substr(0, " + length + ")";
  170. else
  171. return "hotCurrentHash";
  172. });
  173. compilation.mainTemplate.plugin("module-obj", function(source, chunk, hash, varModuleId) {
  174. return this.asString([
  175. source + ",",
  176. "hot: hotCreateModule(" + varModuleId + "),",
  177. "parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),",
  178. "children: []"
  179. ]);
  180. });
  181. params.normalModuleFactory.plugin("parser", function(parser, parserOptions) {
  182. parser.plugin("expression __webpack_hash__", ParserHelpers.toConstantDependency("__webpack_require__.h()"));
  183. parser.plugin("evaluate typeof __webpack_hash__", ParserHelpers.evaluateToString("string"));
  184. parser.plugin("evaluate Identifier module.hot", function(expr) {
  185. return ParserHelpers.evaluateToBoolean(!!this.state.compilation.hotUpdateChunkTemplate)(expr);
  186. });
  187. parser.plugin("call module.hot.accept", function(expr) {
  188. if(!this.state.compilation.hotUpdateChunkTemplate) return false;
  189. if(expr.arguments.length >= 1) {
  190. var arg = this.evaluateExpression(expr.arguments[0]);
  191. var params = [],
  192. requests = [];
  193. if(arg.isString()) {
  194. params = [arg];
  195. } else if(arg.isArray()) {
  196. params = arg.items.filter(function(param) {
  197. return param.isString();
  198. });
  199. }
  200. if(params.length > 0) {
  201. params.forEach(function(param, idx) {
  202. var request = param.string;
  203. var dep = new ModuleHotAcceptDependency(request, param.range);
  204. dep.optional = true;
  205. dep.loc = Object.create(expr.loc);
  206. dep.loc.index = idx;
  207. this.state.module.addDependency(dep);
  208. requests.push(request);
  209. }.bind(this));
  210. if(expr.arguments.length > 1)
  211. this.applyPluginsBailResult("hot accept callback", expr.arguments[1], requests);
  212. else
  213. this.applyPluginsBailResult("hot accept without callback", expr, requests);
  214. }
  215. }
  216. });
  217. parser.plugin("call module.hot.decline", function(expr) {
  218. if(!this.state.compilation.hotUpdateChunkTemplate) return false;
  219. if(expr.arguments.length === 1) {
  220. var arg = this.evaluateExpression(expr.arguments[0]);
  221. var params = [];
  222. if(arg.isString()) {
  223. params = [arg];
  224. } else if(arg.isArray()) {
  225. params = arg.items.filter(function(param) {
  226. return param.isString();
  227. });
  228. }
  229. params.forEach(function(param, idx) {
  230. var dep = new ModuleHotDeclineDependency(param.string, param.range);
  231. dep.optional = true;
  232. dep.loc = Object.create(expr.loc);
  233. dep.loc.index = idx;
  234. this.state.module.addDependency(dep);
  235. }.bind(this));
  236. }
  237. });
  238. parser.plugin("expression module.hot", ParserHelpers.skipTraversal);
  239. });
  240. });
  241. };
  242. var hotInitCode = Template.getFunctionContent(require("./HotModuleReplacement.runtime.js"));