HotModuleReplacementPlugin.js 29 KB

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