PageRenderTime 56ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/node_modules/webpack/lib/HotModuleReplacementPlugin.js

https://bitbucket.org/alan_doyle/movie
JavaScript | 251 lines | 230 code | 17 blank | 4 comment | 39 complexity | 8728e6e3e1944cb569b07d75fa91a46a MD5 | raw file
Possible License(s): CC-BY-SA-3.0, Unlicense, BSD-2-Clause, MIT, BSD-3-Clause, Apache-2.0, CC-BY-4.0, GPL-2.0, 0BSD, JSON
  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("additional-pass", callback => {
  27. if(multiStep)
  28. return setTimeout(callback, fullBuildTimeout);
  29. return callback();
  30. });
  31. compiler.plugin("compilation", (compilation, params) => {
  32. const hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate;
  33. if(!hotUpdateChunkTemplate) return;
  34. const normalModuleFactory = params.normalModuleFactory;
  35. compilation.dependencyFactories.set(ConstDependency, new NullFactory());
  36. compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
  37. compilation.dependencyFactories.set(ModuleHotAcceptDependency, normalModuleFactory);
  38. compilation.dependencyTemplates.set(ModuleHotAcceptDependency, new ModuleHotAcceptDependency.Template());
  39. compilation.dependencyFactories.set(ModuleHotDeclineDependency, normalModuleFactory);
  40. compilation.dependencyTemplates.set(ModuleHotDeclineDependency, new ModuleHotDeclineDependency.Template());
  41. compilation.plugin("record", function(compilation, records) {
  42. if(records.hash === this.hash) return;
  43. records.hash = compilation.hash;
  44. records.moduleHashs = {};
  45. this.modules.forEach(module => {
  46. const identifier = module.identifier();
  47. const hash = require("crypto").createHash("md5");
  48. module.updateHash(hash);
  49. records.moduleHashs[identifier] = hash.digest("hex");
  50. });
  51. records.chunkHashs = {};
  52. this.chunks.forEach(chunk => {
  53. records.chunkHashs[chunk.id] = chunk.hash;
  54. });
  55. records.chunkModuleIds = {};
  56. this.chunks.forEach(chunk => {
  57. records.chunkModuleIds[chunk.id] = chunk.mapModules(m => m.id);
  58. });
  59. });
  60. let initialPass = false;
  61. let recompilation = false;
  62. compilation.plugin("after-hash", function() {
  63. let records = this.records;
  64. if(!records) {
  65. initialPass = true;
  66. return;
  67. }
  68. if(!records.hash)
  69. initialPass = true;
  70. const preHash = records.preHash || "x";
  71. const prepreHash = records.prepreHash || "x";
  72. if(preHash === this.hash) {
  73. recompilation = true;
  74. this.modifyHash(prepreHash);
  75. return;
  76. }
  77. records.prepreHash = records.hash || "x";
  78. records.preHash = this.hash;
  79. this.modifyHash(records.prepreHash);
  80. });
  81. compilation.plugin("should-generate-chunk-assets", () => {
  82. if(multiStep && !recompilation && !initialPass)
  83. return false;
  84. });
  85. compilation.plugin("need-additional-pass", () => {
  86. if(multiStep && !recompilation && !initialPass)
  87. return true;
  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"));