HotModuleReplacementPlugin.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { SyncBailHook } = require("tapable");
  7. const { RawSource } = require("webpack-sources");
  8. const ChunkGraph = require("./ChunkGraph");
  9. const Compilation = require("./Compilation");
  10. const HotUpdateChunk = require("./HotUpdateChunk");
  11. const NormalModule = require("./NormalModule");
  12. const RuntimeGlobals = require("./RuntimeGlobals");
  13. const WebpackError = require("./WebpackError");
  14. const ConstDependency = require("./dependencies/ConstDependency");
  15. const ImportMetaHotAcceptDependency = require("./dependencies/ImportMetaHotAcceptDependency");
  16. const ImportMetaHotDeclineDependency = require("./dependencies/ImportMetaHotDeclineDependency");
  17. const ModuleHotAcceptDependency = require("./dependencies/ModuleHotAcceptDependency");
  18. const ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency");
  19. const HotModuleReplacementRuntimeModule = require("./hmr/HotModuleReplacementRuntimeModule");
  20. const JavascriptParser = require("./javascript/JavascriptParser");
  21. const {
  22. evaluateToIdentifier
  23. } = require("./javascript/JavascriptParserHelpers");
  24. const { find, isSubset } = require("./util/SetHelpers");
  25. const TupleSet = require("./util/TupleSet");
  26. const { compareModulesById } = require("./util/comparators");
  27. const {
  28. getRuntimeKey,
  29. keyToRuntime,
  30. forEachRuntime,
  31. mergeRuntimeOwned,
  32. subtractRuntime,
  33. intersectRuntime
  34. } = require("./util/runtime");
  35. const {
  36. JAVASCRIPT_MODULE_TYPE_AUTO,
  37. JAVASCRIPT_MODULE_TYPE_DYNAMIC,
  38. JAVASCRIPT_MODULE_TYPE_ESM,
  39. WEBPACK_MODULE_TYPE_RUNTIME
  40. } = require("./ModuleTypeConstants");
  41. /** @typedef {import("estree").CallExpression} CallExpression */
  42. /** @typedef {import("estree").Expression} Expression */
  43. /** @typedef {import("./Chunk")} Chunk */
  44. /** @typedef {import("./Chunk").ChunkId} ChunkId */
  45. /** @typedef {import("./Compilation").AssetInfo} AssetInfo */
  46. /** @typedef {import("./Compiler")} Compiler */
  47. /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
  48. /** @typedef {import("./Module")} Module */
  49. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  50. /** @typedef {import("./RuntimeModule")} RuntimeModule */
  51. /** @typedef {import("./javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
  52. /** @typedef {import("./javascript/JavascriptParserHelpers").Range} Range */
  53. /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
  54. /**
  55. * @typedef {object} HMRJavascriptParserHooks
  56. * @property {SyncBailHook<[TODO, string[]], void>} hotAcceptCallback
  57. * @property {SyncBailHook<[TODO, string[]], void>} hotAcceptWithoutCallback
  58. */
  59. /** @typedef {Map<string, { updatedChunkIds: Set<ChunkId>, removedChunkIds: Set<ChunkId>, removedModules: Set<Module>, filename: string, assetInfo: AssetInfo }>} HotUpdateMainContentByRuntime */
  60. /** @type {WeakMap<JavascriptParser, HMRJavascriptParserHooks>} */
  61. const parserHooksMap = new WeakMap();
  62. const PLUGIN_NAME = "HotModuleReplacementPlugin";
  63. class HotModuleReplacementPlugin {
  64. /**
  65. * @param {JavascriptParser} parser the parser
  66. * @returns {HMRJavascriptParserHooks} the attached hooks
  67. */
  68. static getParserHooks(parser) {
  69. if (!(parser instanceof JavascriptParser)) {
  70. throw new TypeError(
  71. "The 'parser' argument must be an instance of JavascriptParser"
  72. );
  73. }
  74. let hooks = parserHooksMap.get(parser);
  75. if (hooks === undefined) {
  76. hooks = {
  77. hotAcceptCallback: new SyncBailHook(["expression", "requests"]),
  78. hotAcceptWithoutCallback: new SyncBailHook(["expression", "requests"])
  79. };
  80. parserHooksMap.set(parser, hooks);
  81. }
  82. return hooks;
  83. }
  84. /**
  85. * @param {object=} options options
  86. */
  87. constructor(options) {
  88. this.options = options || {};
  89. }
  90. /**
  91. * Apply the plugin
  92. * @param {Compiler} compiler the compiler instance
  93. * @returns {void}
  94. */
  95. apply(compiler) {
  96. const { _backCompat: backCompat } = compiler;
  97. if (compiler.options.output.strictModuleErrorHandling === undefined)
  98. compiler.options.output.strictModuleErrorHandling = true;
  99. const runtimeRequirements = [RuntimeGlobals.module];
  100. /**
  101. * @param {JavascriptParser} parser the parser
  102. * @param {typeof ModuleHotAcceptDependency} ParamDependency dependency
  103. * @returns {(expr: CallExpression) => boolean | undefined} callback
  104. */
  105. const createAcceptHandler = (parser, ParamDependency) => {
  106. const { hotAcceptCallback, hotAcceptWithoutCallback } =
  107. HotModuleReplacementPlugin.getParserHooks(parser);
  108. return expr => {
  109. const module = parser.state.module;
  110. const dep = new ConstDependency(
  111. `${module.moduleArgument}.hot.accept`,
  112. /** @type {Range} */ (expr.callee.range),
  113. runtimeRequirements
  114. );
  115. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  116. module.addPresentationalDependency(dep);
  117. /** @type {BuildInfo} */
  118. (module.buildInfo).moduleConcatenationBailout =
  119. "Hot Module Replacement";
  120. if (expr.arguments.length >= 1) {
  121. const arg = parser.evaluateExpression(expr.arguments[0]);
  122. /** @type {BasicEvaluatedExpression[]} */
  123. let params = [];
  124. if (arg.isString()) {
  125. params = [arg];
  126. } else if (arg.isArray()) {
  127. params =
  128. /** @type {BasicEvaluatedExpression[]} */
  129. (arg.items).filter(param => param.isString());
  130. }
  131. /** @type {string[]} */
  132. let requests = [];
  133. if (params.length > 0) {
  134. params.forEach((param, idx) => {
  135. const request = /** @type {string} */ (param.string);
  136. const dep = new ParamDependency(
  137. request,
  138. /** @type {Range} */ (param.range)
  139. );
  140. dep.optional = true;
  141. dep.loc = Object.create(
  142. /** @type {DependencyLocation} */ (expr.loc)
  143. );
  144. dep.loc.index = idx;
  145. module.addDependency(dep);
  146. requests.push(request);
  147. });
  148. if (expr.arguments.length > 1) {
  149. hotAcceptCallback.call(expr.arguments[1], requests);
  150. for (let i = 1; i < expr.arguments.length; i++) {
  151. parser.walkExpression(expr.arguments[i]);
  152. }
  153. return true;
  154. } else {
  155. hotAcceptWithoutCallback.call(expr, requests);
  156. return true;
  157. }
  158. }
  159. }
  160. parser.walkExpressions(expr.arguments);
  161. return true;
  162. };
  163. };
  164. /**
  165. * @param {JavascriptParser} parser the parser
  166. * @param {typeof ModuleHotDeclineDependency} ParamDependency dependency
  167. * @returns {(expr: CallExpression) => boolean | undefined} callback
  168. */
  169. const createDeclineHandler = (parser, ParamDependency) => expr => {
  170. const module = parser.state.module;
  171. const dep = new ConstDependency(
  172. `${module.moduleArgument}.hot.decline`,
  173. /** @type {Range} */ (expr.callee.range),
  174. runtimeRequirements
  175. );
  176. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  177. module.addPresentationalDependency(dep);
  178. /** @type {BuildInfo} */
  179. (module.buildInfo).moduleConcatenationBailout = "Hot Module Replacement";
  180. if (expr.arguments.length === 1) {
  181. const arg = parser.evaluateExpression(expr.arguments[0]);
  182. /** @type {BasicEvaluatedExpression[]} */
  183. let params = [];
  184. if (arg.isString()) {
  185. params = [arg];
  186. } else if (arg.isArray()) {
  187. params =
  188. /** @type {BasicEvaluatedExpression[]} */
  189. (arg.items).filter(param => param.isString());
  190. }
  191. params.forEach((param, idx) => {
  192. const dep = new ParamDependency(
  193. /** @type {string} */ (param.string),
  194. /** @type {Range} */ (param.range)
  195. );
  196. dep.optional = true;
  197. dep.loc = Object.create(/** @type {DependencyLocation} */ (expr.loc));
  198. dep.loc.index = idx;
  199. module.addDependency(dep);
  200. });
  201. }
  202. return true;
  203. };
  204. /**
  205. * @param {JavascriptParser} parser the parser
  206. * @returns {(expr: Expression) => boolean | undefined} callback
  207. */
  208. const createHMRExpressionHandler = parser => expr => {
  209. const module = parser.state.module;
  210. const dep = new ConstDependency(
  211. `${module.moduleArgument}.hot`,
  212. /** @type {Range} */ (expr.range),
  213. runtimeRequirements
  214. );
  215. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  216. module.addPresentationalDependency(dep);
  217. /** @type {BuildInfo} */
  218. (module.buildInfo).moduleConcatenationBailout = "Hot Module Replacement";
  219. return true;
  220. };
  221. /**
  222. * @param {JavascriptParser} parser the parser
  223. * @returns {void}
  224. */
  225. const applyModuleHot = parser => {
  226. parser.hooks.evaluateIdentifier.for("module.hot").tap(
  227. {
  228. name: PLUGIN_NAME,
  229. before: "NodeStuffPlugin"
  230. },
  231. expr => {
  232. return evaluateToIdentifier(
  233. "module.hot",
  234. "module",
  235. () => ["hot"],
  236. true
  237. )(expr);
  238. }
  239. );
  240. parser.hooks.call
  241. .for("module.hot.accept")
  242. .tap(
  243. PLUGIN_NAME,
  244. createAcceptHandler(parser, ModuleHotAcceptDependency)
  245. );
  246. parser.hooks.call
  247. .for("module.hot.decline")
  248. .tap(
  249. PLUGIN_NAME,
  250. createDeclineHandler(parser, ModuleHotDeclineDependency)
  251. );
  252. parser.hooks.expression
  253. .for("module.hot")
  254. .tap(PLUGIN_NAME, createHMRExpressionHandler(parser));
  255. };
  256. /**
  257. * @param {JavascriptParser} parser the parser
  258. * @returns {void}
  259. */
  260. const applyImportMetaHot = parser => {
  261. parser.hooks.evaluateIdentifier
  262. .for("import.meta.webpackHot")
  263. .tap(PLUGIN_NAME, expr => {
  264. return evaluateToIdentifier(
  265. "import.meta.webpackHot",
  266. "import.meta",
  267. () => ["webpackHot"],
  268. true
  269. )(expr);
  270. });
  271. parser.hooks.call
  272. .for("import.meta.webpackHot.accept")
  273. .tap(
  274. PLUGIN_NAME,
  275. createAcceptHandler(parser, ImportMetaHotAcceptDependency)
  276. );
  277. parser.hooks.call
  278. .for("import.meta.webpackHot.decline")
  279. .tap(
  280. PLUGIN_NAME,
  281. createDeclineHandler(parser, ImportMetaHotDeclineDependency)
  282. );
  283. parser.hooks.expression
  284. .for("import.meta.webpackHot")
  285. .tap(PLUGIN_NAME, createHMRExpressionHandler(parser));
  286. };
  287. compiler.hooks.compilation.tap(
  288. PLUGIN_NAME,
  289. (compilation, { normalModuleFactory }) => {
  290. // This applies the HMR plugin only to the targeted compiler
  291. // It should not affect child compilations
  292. if (compilation.compiler !== compiler) return;
  293. //#region module.hot.* API
  294. compilation.dependencyFactories.set(
  295. ModuleHotAcceptDependency,
  296. normalModuleFactory
  297. );
  298. compilation.dependencyTemplates.set(
  299. ModuleHotAcceptDependency,
  300. new ModuleHotAcceptDependency.Template()
  301. );
  302. compilation.dependencyFactories.set(
  303. ModuleHotDeclineDependency,
  304. normalModuleFactory
  305. );
  306. compilation.dependencyTemplates.set(
  307. ModuleHotDeclineDependency,
  308. new ModuleHotDeclineDependency.Template()
  309. );
  310. //#endregion
  311. //#region import.meta.webpackHot.* API
  312. compilation.dependencyFactories.set(
  313. ImportMetaHotAcceptDependency,
  314. normalModuleFactory
  315. );
  316. compilation.dependencyTemplates.set(
  317. ImportMetaHotAcceptDependency,
  318. new ImportMetaHotAcceptDependency.Template()
  319. );
  320. compilation.dependencyFactories.set(
  321. ImportMetaHotDeclineDependency,
  322. normalModuleFactory
  323. );
  324. compilation.dependencyTemplates.set(
  325. ImportMetaHotDeclineDependency,
  326. new ImportMetaHotDeclineDependency.Template()
  327. );
  328. //#endregion
  329. let hotIndex = 0;
  330. /** @type {Record<string, string>} */
  331. const fullHashChunkModuleHashes = {};
  332. /** @type {Record<string, string>} */
  333. const chunkModuleHashes = {};
  334. compilation.hooks.record.tap(PLUGIN_NAME, (compilation, records) => {
  335. if (records.hash === compilation.hash) return;
  336. const chunkGraph = compilation.chunkGraph;
  337. records.hash = compilation.hash;
  338. records.hotIndex = hotIndex;
  339. records.fullHashChunkModuleHashes = fullHashChunkModuleHashes;
  340. records.chunkModuleHashes = chunkModuleHashes;
  341. records.chunkHashes = {};
  342. records.chunkRuntime = {};
  343. for (const chunk of compilation.chunks) {
  344. const chunkId = /** @type {ChunkId} */ (chunk.id);
  345. records.chunkHashes[chunkId] = chunk.hash;
  346. records.chunkRuntime[chunkId] = getRuntimeKey(chunk.runtime);
  347. }
  348. records.chunkModuleIds = {};
  349. for (const chunk of compilation.chunks) {
  350. records.chunkModuleIds[/** @type {ChunkId} */ (chunk.id)] =
  351. Array.from(
  352. chunkGraph.getOrderedChunkModulesIterable(
  353. chunk,
  354. compareModulesById(chunkGraph)
  355. ),
  356. m => chunkGraph.getModuleId(m)
  357. );
  358. }
  359. });
  360. /** @type {TupleSet<[Module, Chunk]>} */
  361. const updatedModules = new TupleSet();
  362. /** @type {TupleSet<[Module, Chunk]>} */
  363. const fullHashModules = new TupleSet();
  364. /** @type {TupleSet<[Module, RuntimeSpec]>} */
  365. const nonCodeGeneratedModules = new TupleSet();
  366. compilation.hooks.fullHash.tap(PLUGIN_NAME, hash => {
  367. const chunkGraph = compilation.chunkGraph;
  368. const records = compilation.records;
  369. for (const chunk of compilation.chunks) {
  370. /**
  371. * @param {Module} module module
  372. * @returns {string} module hash
  373. */
  374. const getModuleHash = module => {
  375. if (
  376. compilation.codeGenerationResults.has(module, chunk.runtime)
  377. ) {
  378. return compilation.codeGenerationResults.getHash(
  379. module,
  380. chunk.runtime
  381. );
  382. } else {
  383. nonCodeGeneratedModules.add(module, chunk.runtime);
  384. return chunkGraph.getModuleHash(module, chunk.runtime);
  385. }
  386. };
  387. const fullHashModulesInThisChunk =
  388. chunkGraph.getChunkFullHashModulesSet(chunk);
  389. if (fullHashModulesInThisChunk !== undefined) {
  390. for (const module of fullHashModulesInThisChunk) {
  391. fullHashModules.add(module, chunk);
  392. }
  393. }
  394. const modules = chunkGraph.getChunkModulesIterable(chunk);
  395. if (modules !== undefined) {
  396. if (records.chunkModuleHashes) {
  397. if (fullHashModulesInThisChunk !== undefined) {
  398. for (const module of modules) {
  399. const key = `${chunk.id}|${module.identifier()}`;
  400. const hash = getModuleHash(module);
  401. if (
  402. fullHashModulesInThisChunk.has(
  403. /** @type {RuntimeModule} */ (module)
  404. )
  405. ) {
  406. if (records.fullHashChunkModuleHashes[key] !== hash) {
  407. updatedModules.add(module, chunk);
  408. }
  409. fullHashChunkModuleHashes[key] = hash;
  410. } else {
  411. if (records.chunkModuleHashes[key] !== hash) {
  412. updatedModules.add(module, chunk);
  413. }
  414. chunkModuleHashes[key] = hash;
  415. }
  416. }
  417. } else {
  418. for (const module of modules) {
  419. const key = `${chunk.id}|${module.identifier()}`;
  420. const hash = getModuleHash(module);
  421. if (records.chunkModuleHashes[key] !== hash) {
  422. updatedModules.add(module, chunk);
  423. }
  424. chunkModuleHashes[key] = hash;
  425. }
  426. }
  427. } else {
  428. if (fullHashModulesInThisChunk !== undefined) {
  429. for (const module of modules) {
  430. const key = `${chunk.id}|${module.identifier()}`;
  431. const hash = getModuleHash(module);
  432. if (
  433. fullHashModulesInThisChunk.has(
  434. /** @type {RuntimeModule} */ (module)
  435. )
  436. ) {
  437. fullHashChunkModuleHashes[key] = hash;
  438. } else {
  439. chunkModuleHashes[key] = hash;
  440. }
  441. }
  442. } else {
  443. for (const module of modules) {
  444. const key = `${chunk.id}|${module.identifier()}`;
  445. const hash = getModuleHash(module);
  446. chunkModuleHashes[key] = hash;
  447. }
  448. }
  449. }
  450. }
  451. }
  452. hotIndex = records.hotIndex || 0;
  453. if (updatedModules.size > 0) hotIndex++;
  454. hash.update(`${hotIndex}`);
  455. });
  456. compilation.hooks.processAssets.tap(
  457. {
  458. name: PLUGIN_NAME,
  459. stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
  460. },
  461. () => {
  462. const chunkGraph = compilation.chunkGraph;
  463. const records = compilation.records;
  464. if (records.hash === compilation.hash) return;
  465. if (
  466. !records.chunkModuleHashes ||
  467. !records.chunkHashes ||
  468. !records.chunkModuleIds
  469. ) {
  470. return;
  471. }
  472. for (const [module, chunk] of fullHashModules) {
  473. const key = `${chunk.id}|${module.identifier()}`;
  474. const hash = nonCodeGeneratedModules.has(module, chunk.runtime)
  475. ? chunkGraph.getModuleHash(module, chunk.runtime)
  476. : compilation.codeGenerationResults.getHash(
  477. module,
  478. chunk.runtime
  479. );
  480. if (records.chunkModuleHashes[key] !== hash) {
  481. updatedModules.add(module, chunk);
  482. }
  483. chunkModuleHashes[key] = hash;
  484. }
  485. /** @type {HotUpdateMainContentByRuntime} */
  486. const hotUpdateMainContentByRuntime = new Map();
  487. let allOldRuntime;
  488. for (const key of Object.keys(records.chunkRuntime)) {
  489. const runtime = keyToRuntime(records.chunkRuntime[key]);
  490. allOldRuntime = mergeRuntimeOwned(allOldRuntime, runtime);
  491. }
  492. forEachRuntime(allOldRuntime, runtime => {
  493. const { path: filename, info: assetInfo } =
  494. compilation.getPathWithInfo(
  495. compilation.outputOptions.hotUpdateMainFilename,
  496. {
  497. hash: records.hash,
  498. runtime
  499. }
  500. );
  501. hotUpdateMainContentByRuntime.set(
  502. /** @type {string} */ (runtime),
  503. {
  504. updatedChunkIds: new Set(),
  505. removedChunkIds: new Set(),
  506. removedModules: new Set(),
  507. filename,
  508. assetInfo
  509. }
  510. );
  511. });
  512. if (hotUpdateMainContentByRuntime.size === 0) return;
  513. // Create a list of all active modules to verify which modules are removed completely
  514. /** @type {Map<number|string, Module>} */
  515. const allModules = new Map();
  516. for (const module of compilation.modules) {
  517. const id = chunkGraph.getModuleId(module);
  518. allModules.set(id, module);
  519. }
  520. // List of completely removed modules
  521. /** @type {Set<string | number>} */
  522. const completelyRemovedModules = new Set();
  523. for (const key of Object.keys(records.chunkHashes)) {
  524. const oldRuntime = keyToRuntime(records.chunkRuntime[key]);
  525. /** @type {Module[]} */
  526. const remainingModules = [];
  527. // Check which modules are removed
  528. for (const id of records.chunkModuleIds[key]) {
  529. const module = allModules.get(id);
  530. if (module === undefined) {
  531. completelyRemovedModules.add(id);
  532. } else {
  533. remainingModules.push(module);
  534. }
  535. }
  536. /** @type {ChunkId | null} */
  537. let chunkId;
  538. let newModules;
  539. let newRuntimeModules;
  540. let newFullHashModules;
  541. let newDependentHashModules;
  542. let newRuntime;
  543. let removedFromRuntime;
  544. const currentChunk = find(
  545. compilation.chunks,
  546. chunk => `${chunk.id}` === key
  547. );
  548. if (currentChunk) {
  549. chunkId = currentChunk.id;
  550. newRuntime = intersectRuntime(
  551. currentChunk.runtime,
  552. allOldRuntime
  553. );
  554. if (newRuntime === undefined) continue;
  555. newModules = chunkGraph
  556. .getChunkModules(currentChunk)
  557. .filter(module => updatedModules.has(module, currentChunk));
  558. newRuntimeModules = Array.from(
  559. chunkGraph.getChunkRuntimeModulesIterable(currentChunk)
  560. ).filter(module => updatedModules.has(module, currentChunk));
  561. const fullHashModules =
  562. chunkGraph.getChunkFullHashModulesIterable(currentChunk);
  563. newFullHashModules =
  564. fullHashModules &&
  565. Array.from(fullHashModules).filter(module =>
  566. updatedModules.has(module, currentChunk)
  567. );
  568. const dependentHashModules =
  569. chunkGraph.getChunkDependentHashModulesIterable(currentChunk);
  570. newDependentHashModules =
  571. dependentHashModules &&
  572. Array.from(dependentHashModules).filter(module =>
  573. updatedModules.has(module, currentChunk)
  574. );
  575. removedFromRuntime = subtractRuntime(oldRuntime, newRuntime);
  576. } else {
  577. // chunk has completely removed
  578. chunkId = `${+key}` === key ? +key : key;
  579. removedFromRuntime = oldRuntime;
  580. newRuntime = oldRuntime;
  581. }
  582. if (removedFromRuntime) {
  583. // chunk was removed from some runtimes
  584. forEachRuntime(removedFromRuntime, runtime => {
  585. const item = hotUpdateMainContentByRuntime.get(
  586. /** @type {string} */ (runtime)
  587. );
  588. item.removedChunkIds.add(/** @type {ChunkId} */ (chunkId));
  589. });
  590. // dispose modules from the chunk in these runtimes
  591. // where they are no longer in this runtime
  592. for (const module of remainingModules) {
  593. const moduleKey = `${key}|${module.identifier()}`;
  594. const oldHash = records.chunkModuleHashes[moduleKey];
  595. const runtimes = chunkGraph.getModuleRuntimes(module);
  596. if (oldRuntime === newRuntime && runtimes.has(newRuntime)) {
  597. // Module is still in the same runtime combination
  598. const hash = nonCodeGeneratedModules.has(module, newRuntime)
  599. ? chunkGraph.getModuleHash(module, newRuntime)
  600. : compilation.codeGenerationResults.getHash(
  601. module,
  602. newRuntime
  603. );
  604. if (hash !== oldHash) {
  605. if (module.type === WEBPACK_MODULE_TYPE_RUNTIME) {
  606. newRuntimeModules = newRuntimeModules || [];
  607. newRuntimeModules.push(
  608. /** @type {RuntimeModule} */ (module)
  609. );
  610. } else {
  611. newModules = newModules || [];
  612. newModules.push(module);
  613. }
  614. }
  615. } else {
  616. // module is no longer in this runtime combination
  617. // We (incorrectly) assume that it's not in an overlapping runtime combination
  618. // and dispose it from the main runtimes the chunk was removed from
  619. forEachRuntime(removedFromRuntime, runtime => {
  620. // If the module is still used in this runtime, do not dispose it
  621. // This could create a bad runtime state where the module is still loaded,
  622. // but no chunk which contains it. This means we don't receive further HMR updates
  623. // to this module and that's bad.
  624. // TODO force load one of the chunks which contains the module
  625. for (const moduleRuntime of runtimes) {
  626. if (typeof moduleRuntime === "string") {
  627. if (moduleRuntime === runtime) return;
  628. } else if (moduleRuntime !== undefined) {
  629. if (
  630. moduleRuntime.has(/** @type {string} */ (runtime))
  631. )
  632. return;
  633. }
  634. }
  635. const item = hotUpdateMainContentByRuntime.get(
  636. /** @type {string} */ (runtime)
  637. );
  638. item.removedModules.add(module);
  639. });
  640. }
  641. }
  642. }
  643. if (
  644. (newModules && newModules.length > 0) ||
  645. (newRuntimeModules && newRuntimeModules.length > 0)
  646. ) {
  647. const hotUpdateChunk = new HotUpdateChunk();
  648. if (backCompat)
  649. ChunkGraph.setChunkGraphForChunk(hotUpdateChunk, chunkGraph);
  650. hotUpdateChunk.id = chunkId;
  651. hotUpdateChunk.runtime = newRuntime;
  652. if (currentChunk) {
  653. for (const group of currentChunk.groupsIterable)
  654. hotUpdateChunk.addGroup(group);
  655. }
  656. chunkGraph.attachModules(hotUpdateChunk, newModules || []);
  657. chunkGraph.attachRuntimeModules(
  658. hotUpdateChunk,
  659. newRuntimeModules || []
  660. );
  661. if (newFullHashModules) {
  662. chunkGraph.attachFullHashModules(
  663. hotUpdateChunk,
  664. newFullHashModules
  665. );
  666. }
  667. if (newDependentHashModules) {
  668. chunkGraph.attachDependentHashModules(
  669. hotUpdateChunk,
  670. newDependentHashModules
  671. );
  672. }
  673. const renderManifest = compilation.getRenderManifest({
  674. chunk: hotUpdateChunk,
  675. hash: records.hash,
  676. fullHash: records.hash,
  677. outputOptions: compilation.outputOptions,
  678. moduleTemplates: compilation.moduleTemplates,
  679. dependencyTemplates: compilation.dependencyTemplates,
  680. codeGenerationResults: compilation.codeGenerationResults,
  681. runtimeTemplate: compilation.runtimeTemplate,
  682. moduleGraph: compilation.moduleGraph,
  683. chunkGraph
  684. });
  685. for (const entry of renderManifest) {
  686. /** @type {string} */
  687. let filename;
  688. /** @type {AssetInfo} */
  689. let assetInfo;
  690. if ("filename" in entry) {
  691. filename = entry.filename;
  692. assetInfo = entry.info;
  693. } else {
  694. ({ path: filename, info: assetInfo } =
  695. compilation.getPathWithInfo(
  696. entry.filenameTemplate,
  697. entry.pathOptions
  698. ));
  699. }
  700. const source = entry.render();
  701. compilation.additionalChunkAssets.push(filename);
  702. compilation.emitAsset(filename, source, {
  703. hotModuleReplacement: true,
  704. ...assetInfo
  705. });
  706. if (currentChunk) {
  707. currentChunk.files.add(filename);
  708. compilation.hooks.chunkAsset.call(currentChunk, filename);
  709. }
  710. }
  711. forEachRuntime(newRuntime, runtime => {
  712. const item = hotUpdateMainContentByRuntime.get(
  713. /** @type {string} */ (runtime)
  714. );
  715. item.updatedChunkIds.add(/** @type {ChunkId} */ (chunkId));
  716. });
  717. }
  718. }
  719. const completelyRemovedModulesArray = Array.from(
  720. completelyRemovedModules
  721. );
  722. const hotUpdateMainContentByFilename = new Map();
  723. for (const {
  724. removedChunkIds,
  725. removedModules,
  726. updatedChunkIds,
  727. filename,
  728. assetInfo
  729. } of hotUpdateMainContentByRuntime.values()) {
  730. const old = hotUpdateMainContentByFilename.get(filename);
  731. if (
  732. old &&
  733. (!isSubset(old.removedChunkIds, removedChunkIds) ||
  734. !isSubset(old.removedModules, removedModules) ||
  735. !isSubset(old.updatedChunkIds, updatedChunkIds))
  736. ) {
  737. compilation.warnings.push(
  738. new WebpackError(`HotModuleReplacementPlugin
  739. The configured output.hotUpdateMainFilename doesn't lead to unique filenames per runtime and HMR update differs between runtimes.
  740. This might lead to incorrect runtime behavior of the applied update.
  741. To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename option, or use the default config.`)
  742. );
  743. for (const chunkId of removedChunkIds)
  744. old.removedChunkIds.add(chunkId);
  745. for (const chunkId of removedModules)
  746. old.removedModules.add(chunkId);
  747. for (const chunkId of updatedChunkIds)
  748. old.updatedChunkIds.add(chunkId);
  749. continue;
  750. }
  751. hotUpdateMainContentByFilename.set(filename, {
  752. removedChunkIds,
  753. removedModules,
  754. updatedChunkIds,
  755. assetInfo
  756. });
  757. }
  758. for (const [
  759. filename,
  760. { removedChunkIds, removedModules, updatedChunkIds, assetInfo }
  761. ] of hotUpdateMainContentByFilename) {
  762. const hotUpdateMainJson = {
  763. c: Array.from(updatedChunkIds),
  764. r: Array.from(removedChunkIds),
  765. m:
  766. removedModules.size === 0
  767. ? completelyRemovedModulesArray
  768. : completelyRemovedModulesArray.concat(
  769. Array.from(removedModules, m =>
  770. chunkGraph.getModuleId(m)
  771. )
  772. )
  773. };
  774. const source = new RawSource(JSON.stringify(hotUpdateMainJson));
  775. compilation.emitAsset(filename, source, {
  776. hotModuleReplacement: true,
  777. ...assetInfo
  778. });
  779. }
  780. }
  781. );
  782. compilation.hooks.additionalTreeRuntimeRequirements.tap(
  783. PLUGIN_NAME,
  784. (chunk, runtimeRequirements) => {
  785. runtimeRequirements.add(RuntimeGlobals.hmrDownloadManifest);
  786. runtimeRequirements.add(RuntimeGlobals.hmrDownloadUpdateHandlers);
  787. runtimeRequirements.add(RuntimeGlobals.interceptModuleExecution);
  788. runtimeRequirements.add(RuntimeGlobals.moduleCache);
  789. compilation.addRuntimeModule(
  790. chunk,
  791. new HotModuleReplacementRuntimeModule()
  792. );
  793. }
  794. );
  795. normalModuleFactory.hooks.parser
  796. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  797. .tap(PLUGIN_NAME, parser => {
  798. applyModuleHot(parser);
  799. applyImportMetaHot(parser);
  800. });
  801. normalModuleFactory.hooks.parser
  802. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  803. .tap(PLUGIN_NAME, parser => {
  804. applyModuleHot(parser);
  805. });
  806. normalModuleFactory.hooks.parser
  807. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  808. .tap(PLUGIN_NAME, parser => {
  809. applyImportMetaHot(parser);
  810. });
  811. NormalModule.getCompilationHooks(compilation).loader.tap(
  812. PLUGIN_NAME,
  813. context => {
  814. context.hot = true;
  815. }
  816. );
  817. }
  818. );
  819. }
  820. }
  821. module.exports = HotModuleReplacementPlugin;