HotModuleReplacementPlugin.js 9.7KB

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