HotModuleReplacementPlugin.js 31 KB

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