JavascriptModulesPlugin.js 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const vm = require("vm");
  7. const eslintScope = require("eslint-scope");
  8. const { SyncBailHook, SyncHook, SyncWaterfallHook } = require("tapable");
  9. const {
  10. CachedSource,
  11. ConcatSource,
  12. OriginalSource,
  13. PrefixSource,
  14. RawSource,
  15. ReplaceSource
  16. } = require("webpack-sources");
  17. const Compilation = require("../Compilation");
  18. const { tryRunOrWebpackError } = require("../HookWebpackError");
  19. const HotUpdateChunk = require("../HotUpdateChunk");
  20. const InitFragment = require("../InitFragment");
  21. const {
  22. JAVASCRIPT_MODULE_TYPE_AUTO,
  23. JAVASCRIPT_MODULE_TYPE_DYNAMIC,
  24. JAVASCRIPT_MODULE_TYPE_ESM,
  25. WEBPACK_MODULE_TYPE_RUNTIME
  26. } = require("../ModuleTypeConstants");
  27. const NormalModule = require("../NormalModule");
  28. const RuntimeGlobals = require("../RuntimeGlobals");
  29. const Template = require("../Template");
  30. const { last, someInIterable } = require("../util/IterableHelpers");
  31. const StringXor = require("../util/StringXor");
  32. const { compareModulesByIdOrIdentifier } = require("../util/comparators");
  33. const {
  34. RESERVED_NAMES,
  35. addScopeSymbols,
  36. findNewName,
  37. getAllReferences,
  38. getPathInAst,
  39. getUsedNamesInScopeInfo
  40. } = require("../util/concatenate");
  41. const createHash = require("../util/createHash");
  42. const nonNumericOnlyHash = require("../util/nonNumericOnlyHash");
  43. const removeBOM = require("../util/removeBOM");
  44. const { intersectRuntime } = require("../util/runtime");
  45. const JavascriptGenerator = require("./JavascriptGenerator");
  46. const JavascriptParser = require("./JavascriptParser");
  47. /** @typedef {import("eslint-scope").Reference} Reference */
  48. /** @typedef {import("eslint-scope").Scope} Scope */
  49. /** @typedef {import("eslint-scope").Variable} Variable */
  50. /** @typedef {import("estree").Program} Program */
  51. /** @typedef {import("webpack-sources").Source} Source */
  52. /** @typedef {import("../../declarations/WebpackOptions").HashFunction} HashFunction */
  53. /** @typedef {import("../../declarations/WebpackOptions").Output} OutputOptions */
  54. /** @typedef {import("../Chunk")} Chunk */
  55. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  56. /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
  57. /** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */
  58. /** @typedef {import("../Compilation").ExecuteModuleObject} ExecuteModuleObject */
  59. /** @typedef {import("../Compiler")} Compiler */
  60. /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
  61. /** @typedef {import("../Entrypoint")} Entrypoint */
  62. /** @typedef {import("../Module")} Module */
  63. /** @typedef {import("../Module").BuildInfo} BuildInfo */
  64. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  65. /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
  66. /** @typedef {import("../TemplatedPathPlugin").TemplatePath} TemplatePath */
  67. /** @typedef {import("../WebpackError")} WebpackError */
  68. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  69. /** @typedef {import("../util/Hash")} Hash */
  70. /**
  71. * @param {Chunk} chunk a chunk
  72. * @param {ChunkGraph} chunkGraph the chunk graph
  73. * @returns {boolean} true, when a JS file is needed for this chunk
  74. */
  75. const chunkHasJs = (chunk, chunkGraph) => {
  76. if (chunkGraph.getNumberOfEntryModules(chunk) > 0) return true;
  77. return Boolean(
  78. chunkGraph.getChunkModulesIterableBySourceType(chunk, "javascript")
  79. );
  80. };
  81. /**
  82. * @param {Chunk} chunk a chunk
  83. * @param {ChunkGraph} chunkGraph the chunk graph
  84. * @returns {boolean} true, when a JS file is needed for this chunk
  85. */
  86. const chunkHasRuntimeOrJs = (chunk, chunkGraph) => {
  87. if (
  88. chunkGraph.getChunkModulesIterableBySourceType(
  89. chunk,
  90. WEBPACK_MODULE_TYPE_RUNTIME
  91. )
  92. ) {
  93. return true;
  94. }
  95. return Boolean(
  96. chunkGraph.getChunkModulesIterableBySourceType(chunk, "javascript")
  97. );
  98. };
  99. /**
  100. * @param {Module} module a module
  101. * @param {string} code the code
  102. * @returns {string} generated code for the stack
  103. */
  104. const printGeneratedCodeForStack = (module, code) => {
  105. const lines = code.split("\n");
  106. const n = `${lines.length}`.length;
  107. return `\n\nGenerated code for ${module.identifier()}\n${lines
  108. .map(
  109. /**
  110. * @param {string} line the line
  111. * @param {number} i the index
  112. * @param {string[]} _lines the lines
  113. * @returns {string} the line with line number
  114. */
  115. (line, i, _lines) => {
  116. const iStr = `${i + 1}`;
  117. return `${" ".repeat(n - iStr.length)}${iStr} | ${line}`;
  118. }
  119. )
  120. .join("\n")}`;
  121. };
  122. /**
  123. * @typedef {object} RenderContext
  124. * @property {Chunk} chunk the chunk
  125. * @property {DependencyTemplates} dependencyTemplates the dependency templates
  126. * @property {RuntimeTemplate} runtimeTemplate the runtime template
  127. * @property {ModuleGraph} moduleGraph the module graph
  128. * @property {ChunkGraph} chunkGraph the chunk graph
  129. * @property {CodeGenerationResults} codeGenerationResults results of code generation
  130. * @property {boolean | undefined} strictMode rendering in strict context
  131. */
  132. /**
  133. * @typedef {object} MainRenderContext
  134. * @property {Chunk} chunk the chunk
  135. * @property {DependencyTemplates} dependencyTemplates the dependency templates
  136. * @property {RuntimeTemplate} runtimeTemplate the runtime template
  137. * @property {ModuleGraph} moduleGraph the module graph
  138. * @property {ChunkGraph} chunkGraph the chunk graph
  139. * @property {CodeGenerationResults} codeGenerationResults results of code generation
  140. * @property {string} hash hash to be used for render call
  141. * @property {boolean | undefined} strictMode rendering in strict context
  142. */
  143. /**
  144. * @typedef {object} ChunkRenderContext
  145. * @property {Chunk} chunk the chunk
  146. * @property {DependencyTemplates} dependencyTemplates the dependency templates
  147. * @property {RuntimeTemplate} runtimeTemplate the runtime template
  148. * @property {ModuleGraph} moduleGraph the module graph
  149. * @property {ChunkGraph} chunkGraph the chunk graph
  150. * @property {CodeGenerationResults} codeGenerationResults results of code generation
  151. * @property {InitFragment<ChunkRenderContext>[]} chunkInitFragments init fragments for the chunk
  152. * @property {boolean | undefined} strictMode rendering in strict context
  153. */
  154. /**
  155. * @typedef {object} RenderBootstrapContext
  156. * @property {Chunk} chunk the chunk
  157. * @property {CodeGenerationResults} codeGenerationResults results of code generation
  158. * @property {RuntimeTemplate} runtimeTemplate the runtime template
  159. * @property {ModuleGraph} moduleGraph the module graph
  160. * @property {ChunkGraph} chunkGraph the chunk graph
  161. * @property {string} hash hash to be used for render call
  162. */
  163. /**
  164. * @typedef {object} StartupRenderContext
  165. * @property {Chunk} chunk the chunk
  166. * @property {DependencyTemplates} dependencyTemplates the dependency templates
  167. * @property {RuntimeTemplate} runtimeTemplate the runtime template
  168. * @property {ModuleGraph} moduleGraph the module graph
  169. * @property {ChunkGraph} chunkGraph the chunk graph
  170. * @property {CodeGenerationResults} codeGenerationResults results of code generation
  171. * @property {boolean | undefined} strictMode rendering in strict context
  172. * @property {boolean } inlined inlined
  173. * @property {boolean=} inlinedInIIFE the inlined entry module is wrapped in an IIFE
  174. */
  175. /**
  176. * @typedef {object} ModuleRenderContext
  177. * @property {Chunk} chunk the chunk
  178. * @property {DependencyTemplates} dependencyTemplates the dependency templates
  179. * @property {RuntimeTemplate} runtimeTemplate the runtime template
  180. * @property {ModuleGraph} moduleGraph the module graph
  181. * @property {ChunkGraph} chunkGraph the chunk graph
  182. * @property {CodeGenerationResults} codeGenerationResults results of code generation
  183. * @property {InitFragment<ChunkRenderContext>[]} chunkInitFragments init fragments for the chunk
  184. * @property {boolean | undefined} strictMode rendering in strict context
  185. * @property {boolean} factory true: renders as factory method, false: pure module content
  186. * @property {boolean=} inlinedInIIFE the inlined entry module is wrapped in an IIFE, existing only when `factory` is set to false
  187. */
  188. /**
  189. * @typedef {object} CompilationHooks
  190. * @property {SyncWaterfallHook<[Source, Module, ModuleRenderContext]>} renderModuleContent
  191. * @property {SyncWaterfallHook<[Source, Module, ModuleRenderContext]>} renderModuleContainer
  192. * @property {SyncWaterfallHook<[Source, Module, ModuleRenderContext]>} renderModulePackage
  193. * @property {SyncWaterfallHook<[Source, RenderContext]>} renderChunk
  194. * @property {SyncWaterfallHook<[Source, RenderContext]>} renderMain
  195. * @property {SyncWaterfallHook<[Source, RenderContext]>} renderContent
  196. * @property {SyncWaterfallHook<[Source, RenderContext]>} render
  197. * @property {SyncWaterfallHook<[Source, Module, StartupRenderContext]>} renderStartup
  198. * @property {SyncWaterfallHook<[string, RenderBootstrapContext]>} renderRequire
  199. * @property {SyncBailHook<[Module, Partial<RenderBootstrapContext>], string | void>} inlineInRuntimeBailout
  200. * @property {SyncBailHook<[Module, RenderContext], string | void>} embedInRuntimeBailout
  201. * @property {SyncBailHook<[RenderContext], string | void>} strictRuntimeBailout
  202. * @property {SyncHook<[Chunk, Hash, ChunkHashContext]>} chunkHash
  203. * @property {SyncBailHook<[Chunk, RenderContext], boolean | void>} useSourceMap
  204. */
  205. /** @type {WeakMap<Compilation, CompilationHooks>} */
  206. const compilationHooksMap = new WeakMap();
  207. const PLUGIN_NAME = "JavascriptModulesPlugin";
  208. /** @typedef {{ header: string[], beforeStartup: string[], startup: string[], afterStartup: string[], allowInlineStartup: boolean }} Bootstrap */
  209. class JavascriptModulesPlugin {
  210. /**
  211. * @param {Compilation} compilation the compilation
  212. * @returns {CompilationHooks} the attached hooks
  213. */
  214. static getCompilationHooks(compilation) {
  215. if (!(compilation instanceof Compilation)) {
  216. throw new TypeError(
  217. "The 'compilation' argument must be an instance of Compilation"
  218. );
  219. }
  220. let hooks = compilationHooksMap.get(compilation);
  221. if (hooks === undefined) {
  222. hooks = {
  223. renderModuleContent: new SyncWaterfallHook([
  224. "source",
  225. "module",
  226. "moduleRenderContext"
  227. ]),
  228. renderModuleContainer: new SyncWaterfallHook([
  229. "source",
  230. "module",
  231. "moduleRenderContext"
  232. ]),
  233. renderModulePackage: new SyncWaterfallHook([
  234. "source",
  235. "module",
  236. "moduleRenderContext"
  237. ]),
  238. render: new SyncWaterfallHook(["source", "renderContext"]),
  239. renderContent: new SyncWaterfallHook(["source", "renderContext"]),
  240. renderStartup: new SyncWaterfallHook([
  241. "source",
  242. "module",
  243. "startupRenderContext"
  244. ]),
  245. renderChunk: new SyncWaterfallHook(["source", "renderContext"]),
  246. renderMain: new SyncWaterfallHook(["source", "renderContext"]),
  247. renderRequire: new SyncWaterfallHook(["code", "renderContext"]),
  248. inlineInRuntimeBailout: new SyncBailHook(["module", "renderContext"]),
  249. embedInRuntimeBailout: new SyncBailHook(["module", "renderContext"]),
  250. strictRuntimeBailout: new SyncBailHook(["renderContext"]),
  251. chunkHash: new SyncHook(["chunk", "hash", "context"]),
  252. useSourceMap: new SyncBailHook(["chunk", "renderContext"])
  253. };
  254. compilationHooksMap.set(compilation, hooks);
  255. }
  256. return hooks;
  257. }
  258. constructor(options = {}) {
  259. this.options = options;
  260. /** @type {WeakMap<Source, { source: Source, needModule:boolean, needExports: boolean, needRequire: boolean, needThisAsExports: boolean, needStrict: boolean | undefined }>} */
  261. this._moduleFactoryCache = new WeakMap();
  262. }
  263. /**
  264. * Apply the plugin
  265. * @param {Compiler} compiler the compiler instance
  266. * @returns {void}
  267. */
  268. apply(compiler) {
  269. compiler.hooks.compilation.tap(
  270. PLUGIN_NAME,
  271. (compilation, { normalModuleFactory }) => {
  272. const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
  273. for (const type of [
  274. JAVASCRIPT_MODULE_TYPE_AUTO,
  275. JAVASCRIPT_MODULE_TYPE_DYNAMIC,
  276. JAVASCRIPT_MODULE_TYPE_ESM
  277. ]) {
  278. normalModuleFactory.hooks.createParser
  279. .for(type)
  280. .tap(PLUGIN_NAME, (_options) => {
  281. switch (type) {
  282. case JAVASCRIPT_MODULE_TYPE_AUTO: {
  283. return new JavascriptParser("auto");
  284. }
  285. case JAVASCRIPT_MODULE_TYPE_DYNAMIC: {
  286. return new JavascriptParser("script");
  287. }
  288. case JAVASCRIPT_MODULE_TYPE_ESM: {
  289. return new JavascriptParser("module");
  290. }
  291. }
  292. });
  293. normalModuleFactory.hooks.createGenerator
  294. .for(type)
  295. .tap(PLUGIN_NAME, () => new JavascriptGenerator());
  296. NormalModule.getCompilationHooks(compilation).processResult.tap(
  297. PLUGIN_NAME,
  298. (result, module) => {
  299. if (module.type === type) {
  300. const [source, ...rest] = result;
  301. return [removeBOM(source), ...rest];
  302. }
  303. return result;
  304. }
  305. );
  306. }
  307. compilation.hooks.renderManifest.tap(PLUGIN_NAME, (result, options) => {
  308. const {
  309. hash,
  310. chunk,
  311. chunkGraph,
  312. moduleGraph,
  313. runtimeTemplate,
  314. dependencyTemplates,
  315. outputOptions,
  316. codeGenerationResults
  317. } = options;
  318. const hotUpdateChunk = chunk instanceof HotUpdateChunk ? chunk : null;
  319. const filenameTemplate =
  320. JavascriptModulesPlugin.getChunkFilenameTemplate(
  321. chunk,
  322. outputOptions
  323. );
  324. let render;
  325. if (hotUpdateChunk) {
  326. render = () =>
  327. this.renderChunk(
  328. {
  329. chunk,
  330. dependencyTemplates,
  331. runtimeTemplate,
  332. moduleGraph,
  333. chunkGraph,
  334. codeGenerationResults,
  335. strictMode: runtimeTemplate.isModule()
  336. },
  337. hooks
  338. );
  339. } else if (chunk.hasRuntime()) {
  340. if (!chunkHasRuntimeOrJs(chunk, chunkGraph)) {
  341. return result;
  342. }
  343. render = () =>
  344. this.renderMain(
  345. {
  346. hash,
  347. chunk,
  348. dependencyTemplates,
  349. runtimeTemplate,
  350. moduleGraph,
  351. chunkGraph,
  352. codeGenerationResults,
  353. strictMode: runtimeTemplate.isModule()
  354. },
  355. hooks,
  356. compilation
  357. );
  358. } else {
  359. if (!chunkHasJs(chunk, chunkGraph)) {
  360. return result;
  361. }
  362. render = () =>
  363. this.renderChunk(
  364. {
  365. chunk,
  366. dependencyTemplates,
  367. runtimeTemplate,
  368. moduleGraph,
  369. chunkGraph,
  370. codeGenerationResults,
  371. strictMode: runtimeTemplate.isModule()
  372. },
  373. hooks
  374. );
  375. }
  376. result.push({
  377. render,
  378. filenameTemplate,
  379. pathOptions: {
  380. hash,
  381. runtime: chunk.runtime,
  382. chunk,
  383. contentHashType: "javascript"
  384. },
  385. info: {
  386. javascriptModule: compilation.runtimeTemplate.isModule()
  387. },
  388. identifier: hotUpdateChunk
  389. ? `hotupdatechunk${chunk.id}`
  390. : `chunk${chunk.id}`,
  391. hash: chunk.contentHash.javascript
  392. });
  393. return result;
  394. });
  395. compilation.hooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash, context) => {
  396. hooks.chunkHash.call(chunk, hash, context);
  397. if (chunk.hasRuntime()) {
  398. this.updateHashWithBootstrap(
  399. hash,
  400. {
  401. hash: "0000",
  402. chunk,
  403. codeGenerationResults: context.codeGenerationResults,
  404. chunkGraph: context.chunkGraph,
  405. moduleGraph: context.moduleGraph,
  406. runtimeTemplate: context.runtimeTemplate
  407. },
  408. hooks
  409. );
  410. }
  411. });
  412. compilation.hooks.contentHash.tap(PLUGIN_NAME, (chunk) => {
  413. const {
  414. chunkGraph,
  415. codeGenerationResults,
  416. moduleGraph,
  417. runtimeTemplate,
  418. outputOptions: {
  419. hashSalt,
  420. hashDigest,
  421. hashDigestLength,
  422. hashFunction
  423. }
  424. } = compilation;
  425. const hash = createHash(/** @type {HashFunction} */ (hashFunction));
  426. if (hashSalt) hash.update(hashSalt);
  427. if (chunk.hasRuntime()) {
  428. this.updateHashWithBootstrap(
  429. hash,
  430. {
  431. hash: "0000",
  432. chunk,
  433. codeGenerationResults,
  434. chunkGraph: compilation.chunkGraph,
  435. moduleGraph: compilation.moduleGraph,
  436. runtimeTemplate: compilation.runtimeTemplate
  437. },
  438. hooks
  439. );
  440. } else {
  441. hash.update(`${chunk.id} `);
  442. hash.update(chunk.ids ? chunk.ids.join(",") : "");
  443. }
  444. hooks.chunkHash.call(chunk, hash, {
  445. chunkGraph,
  446. codeGenerationResults,
  447. moduleGraph,
  448. runtimeTemplate
  449. });
  450. const modules = chunkGraph.getChunkModulesIterableBySourceType(
  451. chunk,
  452. "javascript"
  453. );
  454. if (modules) {
  455. const xor = new StringXor();
  456. for (const m of modules) {
  457. xor.add(chunkGraph.getModuleHash(m, chunk.runtime));
  458. }
  459. xor.updateHash(hash);
  460. }
  461. const runtimeModules = chunkGraph.getChunkModulesIterableBySourceType(
  462. chunk,
  463. WEBPACK_MODULE_TYPE_RUNTIME
  464. );
  465. if (runtimeModules) {
  466. const xor = new StringXor();
  467. for (const m of runtimeModules) {
  468. xor.add(chunkGraph.getModuleHash(m, chunk.runtime));
  469. }
  470. xor.updateHash(hash);
  471. }
  472. const digest = /** @type {string} */ (hash.digest(hashDigest));
  473. chunk.contentHash.javascript = nonNumericOnlyHash(
  474. digest,
  475. /** @type {number} */
  476. (hashDigestLength)
  477. );
  478. });
  479. compilation.hooks.additionalTreeRuntimeRequirements.tap(
  480. PLUGIN_NAME,
  481. (chunk, set, { chunkGraph }) => {
  482. if (
  483. !set.has(RuntimeGlobals.startupNoDefault) &&
  484. chunkGraph.hasChunkEntryDependentChunks(chunk)
  485. ) {
  486. set.add(RuntimeGlobals.onChunksLoaded);
  487. set.add(RuntimeGlobals.exports);
  488. set.add(RuntimeGlobals.require);
  489. }
  490. }
  491. );
  492. compilation.hooks.executeModule.tap(PLUGIN_NAME, (options, context) => {
  493. const source = options.codeGenerationResult.sources.get("javascript");
  494. if (source === undefined) return;
  495. const { module } = options;
  496. const code = source.source();
  497. const fn = vm.runInThisContext(
  498. `(function(${module.moduleArgument}, ${module.exportsArgument}, ${RuntimeGlobals.require}) {\n${code}\n/**/})`,
  499. {
  500. filename: module.identifier(),
  501. lineOffset: -1
  502. }
  503. );
  504. const moduleObject =
  505. /** @type {ExecuteModuleObject} */
  506. (options.moduleObject);
  507. try {
  508. fn.call(
  509. moduleObject.exports,
  510. moduleObject,
  511. moduleObject.exports,
  512. context.__webpack_require__
  513. );
  514. } catch (err) {
  515. /** @type {Error} */
  516. (err).stack += printGeneratedCodeForStack(
  517. options.module,
  518. /** @type {string} */ (code)
  519. );
  520. throw err;
  521. }
  522. });
  523. compilation.hooks.executeModule.tap(PLUGIN_NAME, (options, context) => {
  524. const source = options.codeGenerationResult.sources.get("runtime");
  525. if (source === undefined) return;
  526. let code = source.source();
  527. if (typeof code !== "string") code = code.toString();
  528. const fn = vm.runInThisContext(
  529. `(function(${RuntimeGlobals.require}) {\n${code}\n/**/})`,
  530. {
  531. filename: options.module.identifier(),
  532. lineOffset: -1
  533. }
  534. );
  535. try {
  536. // eslint-disable-next-line no-useless-call
  537. fn.call(null, context.__webpack_require__);
  538. } catch (err) {
  539. /** @type {Error} */
  540. (err).stack += printGeneratedCodeForStack(options.module, code);
  541. throw err;
  542. }
  543. });
  544. }
  545. );
  546. }
  547. /**
  548. * @param {Chunk} chunk chunk
  549. * @param {OutputOptions} outputOptions output options
  550. * @returns {TemplatePath} used filename template
  551. */
  552. static getChunkFilenameTemplate(chunk, outputOptions) {
  553. if (chunk.filenameTemplate) {
  554. return chunk.filenameTemplate;
  555. } else if (chunk instanceof HotUpdateChunk) {
  556. return /** @type {TemplatePath} */ (outputOptions.hotUpdateChunkFilename);
  557. } else if (chunk.canBeInitial()) {
  558. return /** @type {TemplatePath} */ (outputOptions.filename);
  559. }
  560. return /** @type {TemplatePath} */ (outputOptions.chunkFilename);
  561. }
  562. /**
  563. * @param {Module} module the rendered module
  564. * @param {ModuleRenderContext} renderContext options object
  565. * @param {CompilationHooks} hooks hooks
  566. * @returns {Source | null} the newly generated source from rendering
  567. */
  568. renderModule(module, renderContext, hooks) {
  569. const {
  570. chunk,
  571. chunkGraph,
  572. runtimeTemplate,
  573. codeGenerationResults,
  574. strictMode,
  575. factory
  576. } = renderContext;
  577. try {
  578. const codeGenResult = codeGenerationResults.get(module, chunk.runtime);
  579. const moduleSource = codeGenResult.sources.get("javascript");
  580. if (!moduleSource) return null;
  581. if (codeGenResult.data !== undefined) {
  582. const chunkInitFragments = codeGenResult.data.get("chunkInitFragments");
  583. if (chunkInitFragments) {
  584. for (const i of chunkInitFragments) {
  585. renderContext.chunkInitFragments.push(i);
  586. }
  587. }
  588. }
  589. const moduleSourcePostContent = tryRunOrWebpackError(
  590. () =>
  591. hooks.renderModuleContent.call(moduleSource, module, renderContext),
  592. "JavascriptModulesPlugin.getCompilationHooks().renderModuleContent"
  593. );
  594. let moduleSourcePostContainer;
  595. if (factory) {
  596. const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements(
  597. module,
  598. chunk.runtime
  599. );
  600. const needModule = runtimeRequirements.has(RuntimeGlobals.module);
  601. const needExports = runtimeRequirements.has(RuntimeGlobals.exports);
  602. const needRequire =
  603. runtimeRequirements.has(RuntimeGlobals.require) ||
  604. runtimeRequirements.has(RuntimeGlobals.requireScope);
  605. const needThisAsExports = runtimeRequirements.has(
  606. RuntimeGlobals.thisAsExports
  607. );
  608. const needStrict =
  609. /** @type {BuildInfo} */
  610. (module.buildInfo).strict && !strictMode;
  611. const cacheEntry = this._moduleFactoryCache.get(
  612. moduleSourcePostContent
  613. );
  614. let source;
  615. if (
  616. cacheEntry &&
  617. cacheEntry.needModule === needModule &&
  618. cacheEntry.needExports === needExports &&
  619. cacheEntry.needRequire === needRequire &&
  620. cacheEntry.needThisAsExports === needThisAsExports &&
  621. cacheEntry.needStrict === needStrict
  622. ) {
  623. source = cacheEntry.source;
  624. } else {
  625. const factorySource = new ConcatSource();
  626. const args = [];
  627. if (needExports || needRequire || needModule) {
  628. args.push(
  629. needModule
  630. ? module.moduleArgument
  631. : `__unused_webpack_${module.moduleArgument}`
  632. );
  633. }
  634. if (needExports || needRequire) {
  635. args.push(
  636. needExports
  637. ? module.exportsArgument
  638. : `__unused_webpack_${module.exportsArgument}`
  639. );
  640. }
  641. if (needRequire) args.push(RuntimeGlobals.require);
  642. if (!needThisAsExports && runtimeTemplate.supportsArrowFunction()) {
  643. factorySource.add(`/***/ ((${args.join(", ")}) => {\n\n`);
  644. } else {
  645. factorySource.add(`/***/ (function(${args.join(", ")}) {\n\n`);
  646. }
  647. if (needStrict) {
  648. factorySource.add('"use strict";\n');
  649. }
  650. factorySource.add(moduleSourcePostContent);
  651. factorySource.add("\n\n/***/ })");
  652. source = new CachedSource(factorySource);
  653. this._moduleFactoryCache.set(moduleSourcePostContent, {
  654. source,
  655. needModule,
  656. needExports,
  657. needRequire,
  658. needThisAsExports,
  659. needStrict
  660. });
  661. }
  662. moduleSourcePostContainer = tryRunOrWebpackError(
  663. () => hooks.renderModuleContainer.call(source, module, renderContext),
  664. "JavascriptModulesPlugin.getCompilationHooks().renderModuleContainer"
  665. );
  666. } else {
  667. moduleSourcePostContainer = moduleSourcePostContent;
  668. }
  669. return tryRunOrWebpackError(
  670. () =>
  671. hooks.renderModulePackage.call(
  672. moduleSourcePostContainer,
  673. module,
  674. renderContext
  675. ),
  676. "JavascriptModulesPlugin.getCompilationHooks().renderModulePackage"
  677. );
  678. } catch (err) {
  679. /** @type {WebpackError} */
  680. (err).module = module;
  681. throw err;
  682. }
  683. }
  684. /**
  685. * @param {RenderContext} renderContext the render context
  686. * @param {CompilationHooks} hooks hooks
  687. * @returns {Source} the rendered source
  688. */
  689. renderChunk(renderContext, hooks) {
  690. const { chunk, chunkGraph } = renderContext;
  691. const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType(
  692. chunk,
  693. "javascript",
  694. compareModulesByIdOrIdentifier(chunkGraph)
  695. );
  696. const allModules = modules ? [...modules] : [];
  697. let strictHeader;
  698. let allStrict = renderContext.strictMode;
  699. if (
  700. !allStrict &&
  701. allModules.every((m) => /** @type {BuildInfo} */ (m.buildInfo).strict)
  702. ) {
  703. const strictBailout = hooks.strictRuntimeBailout.call(renderContext);
  704. strictHeader = strictBailout
  705. ? `// runtime can't be in strict mode because ${strictBailout}.\n`
  706. : '"use strict";\n';
  707. if (!strictBailout) allStrict = true;
  708. }
  709. /** @type {ChunkRenderContext} */
  710. const chunkRenderContext = {
  711. ...renderContext,
  712. chunkInitFragments: [],
  713. strictMode: allStrict
  714. };
  715. const moduleSources =
  716. Template.renderChunkModules(chunkRenderContext, allModules, (module) =>
  717. this.renderModule(
  718. module,
  719. { ...chunkRenderContext, factory: true },
  720. hooks
  721. )
  722. ) || new RawSource("{}");
  723. let source = tryRunOrWebpackError(
  724. () => hooks.renderChunk.call(moduleSources, chunkRenderContext),
  725. "JavascriptModulesPlugin.getCompilationHooks().renderChunk"
  726. );
  727. source = tryRunOrWebpackError(
  728. () => hooks.renderContent.call(source, chunkRenderContext),
  729. "JavascriptModulesPlugin.getCompilationHooks().renderContent"
  730. );
  731. if (!source) {
  732. throw new Error(
  733. "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something"
  734. );
  735. }
  736. source = InitFragment.addToSource(
  737. source,
  738. chunkRenderContext.chunkInitFragments,
  739. chunkRenderContext
  740. );
  741. source = tryRunOrWebpackError(
  742. () => hooks.render.call(source, chunkRenderContext),
  743. "JavascriptModulesPlugin.getCompilationHooks().render"
  744. );
  745. if (!source) {
  746. throw new Error(
  747. "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something"
  748. );
  749. }
  750. chunk.rendered = true;
  751. return strictHeader
  752. ? new ConcatSource(strictHeader, source, ";")
  753. : renderContext.runtimeTemplate.isModule()
  754. ? source
  755. : new ConcatSource(source, ";");
  756. }
  757. /**
  758. * @param {MainRenderContext} renderContext options object
  759. * @param {CompilationHooks} hooks hooks
  760. * @param {Compilation} compilation the compilation
  761. * @returns {Source} the newly generated source from rendering
  762. */
  763. renderMain(renderContext, hooks, compilation) {
  764. const { chunk, chunkGraph, runtimeTemplate } = renderContext;
  765. const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk);
  766. const iife = runtimeTemplate.isIIFE();
  767. const bootstrap = this.renderBootstrap(renderContext, hooks);
  768. const useSourceMap = hooks.useSourceMap.call(chunk, renderContext);
  769. /** @type {Module[]} */
  770. const allModules = [
  771. ...(chunkGraph.getOrderedChunkModulesIterableBySourceType(
  772. chunk,
  773. "javascript",
  774. compareModulesByIdOrIdentifier(chunkGraph)
  775. ) || [])
  776. ];
  777. const hasEntryModules = chunkGraph.getNumberOfEntryModules(chunk) > 0;
  778. /** @type {Set<Module> | undefined} */
  779. let inlinedModules;
  780. if (bootstrap.allowInlineStartup && hasEntryModules) {
  781. inlinedModules = new Set(chunkGraph.getChunkEntryModulesIterable(chunk));
  782. }
  783. const source = new ConcatSource();
  784. let prefix;
  785. if (iife) {
  786. if (runtimeTemplate.supportsArrowFunction()) {
  787. source.add("/******/ (() => { // webpackBootstrap\n");
  788. } else {
  789. source.add("/******/ (function() { // webpackBootstrap\n");
  790. }
  791. prefix = "/******/ \t";
  792. } else {
  793. prefix = "/******/ ";
  794. }
  795. let allStrict = renderContext.strictMode;
  796. if (
  797. !allStrict &&
  798. allModules.every((m) => /** @type {BuildInfo} */ (m.buildInfo).strict)
  799. ) {
  800. const strictBailout = hooks.strictRuntimeBailout.call(renderContext);
  801. if (strictBailout) {
  802. source.add(
  803. `${
  804. prefix
  805. }// runtime can't be in strict mode because ${strictBailout}.\n`
  806. );
  807. } else {
  808. allStrict = true;
  809. source.add(`${prefix}"use strict";\n`);
  810. }
  811. }
  812. /** @type {ChunkRenderContext} */
  813. const chunkRenderContext = {
  814. ...renderContext,
  815. chunkInitFragments: [],
  816. strictMode: allStrict
  817. };
  818. const chunkModules = Template.renderChunkModules(
  819. chunkRenderContext,
  820. inlinedModules
  821. ? allModules.filter(
  822. (m) => !(/** @type {Set<Module>} */ (inlinedModules).has(m))
  823. )
  824. : allModules,
  825. (module) =>
  826. this.renderModule(
  827. module,
  828. { ...chunkRenderContext, factory: true },
  829. hooks
  830. ),
  831. prefix
  832. );
  833. if (
  834. chunkModules ||
  835. runtimeRequirements.has(RuntimeGlobals.moduleFactories) ||
  836. runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) ||
  837. runtimeRequirements.has(RuntimeGlobals.require)
  838. ) {
  839. source.add(`${prefix}var __webpack_modules__ = (`);
  840. source.add(chunkModules || "{}");
  841. source.add(");\n");
  842. source.add(
  843. "/************************************************************************/\n"
  844. );
  845. }
  846. if (bootstrap.header.length > 0) {
  847. const header = `${Template.asString(bootstrap.header)}\n`;
  848. source.add(
  849. new PrefixSource(
  850. prefix,
  851. useSourceMap
  852. ? new OriginalSource(header, "webpack/bootstrap")
  853. : new RawSource(header)
  854. )
  855. );
  856. source.add(
  857. "/************************************************************************/\n"
  858. );
  859. }
  860. const runtimeModules =
  861. renderContext.chunkGraph.getChunkRuntimeModulesInOrder(chunk);
  862. if (runtimeModules.length > 0) {
  863. source.add(
  864. new PrefixSource(
  865. prefix,
  866. Template.renderRuntimeModules(runtimeModules, chunkRenderContext)
  867. )
  868. );
  869. source.add(
  870. "/************************************************************************/\n"
  871. );
  872. // runtimeRuntimeModules calls codeGeneration
  873. for (const module of runtimeModules) {
  874. compilation.codeGeneratedModules.add(module);
  875. }
  876. }
  877. if (inlinedModules) {
  878. if (bootstrap.beforeStartup.length > 0) {
  879. const beforeStartup = `${Template.asString(bootstrap.beforeStartup)}\n`;
  880. source.add(
  881. new PrefixSource(
  882. prefix,
  883. useSourceMap
  884. ? new OriginalSource(beforeStartup, "webpack/before-startup")
  885. : new RawSource(beforeStartup)
  886. )
  887. );
  888. }
  889. const lastInlinedModule = /** @type {Module} */ (last(inlinedModules));
  890. const startupSource = new ConcatSource();
  891. if (runtimeRequirements.has(RuntimeGlobals.exports)) {
  892. startupSource.add(`var ${RuntimeGlobals.exports} = {};\n`);
  893. }
  894. const avoidEntryIife = compilation.options.optimization.avoidEntryIife;
  895. /** @type {Map<Module, Source> | false} */
  896. let renamedInlinedModule = false;
  897. let inlinedInIIFE = false;
  898. if (avoidEntryIife) {
  899. renamedInlinedModule = this.getRenamedInlineModule(
  900. allModules,
  901. renderContext,
  902. inlinedModules,
  903. chunkRenderContext,
  904. hooks,
  905. allStrict,
  906. Boolean(chunkModules)
  907. );
  908. }
  909. for (const m of inlinedModules) {
  910. const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements(
  911. m,
  912. chunk.runtime
  913. );
  914. const exports = runtimeRequirements.has(RuntimeGlobals.exports);
  915. const webpackExports =
  916. exports && m.exportsArgument === RuntimeGlobals.exports;
  917. const innerStrict =
  918. !allStrict && /** @type {BuildInfo} */ (m.buildInfo).strict;
  919. const iife = innerStrict
  920. ? "it needs to be in strict mode."
  921. : inlinedModules.size > 1
  922. ? // TODO check globals and top-level declarations of other entries and chunk modules
  923. // to make a better decision
  924. "it needs to be isolated against other entry modules."
  925. : chunkModules && !renamedInlinedModule
  926. ? "it needs to be isolated against other modules in the chunk."
  927. : exports && !webpackExports
  928. ? `it uses a non-standard name for the exports (${m.exportsArgument}).`
  929. : hooks.embedInRuntimeBailout.call(m, renderContext);
  930. if (iife) {
  931. inlinedInIIFE = true;
  932. }
  933. const renderedModule = renamedInlinedModule
  934. ? renamedInlinedModule.get(m)
  935. : this.renderModule(
  936. m,
  937. {
  938. ...chunkRenderContext,
  939. factory: false,
  940. inlinedInIIFE
  941. },
  942. hooks
  943. );
  944. if (renderedModule) {
  945. let footer;
  946. if (iife !== undefined) {
  947. startupSource.add(
  948. `// This entry needs to be wrapped in an IIFE because ${iife}\n`
  949. );
  950. const arrow = runtimeTemplate.supportsArrowFunction();
  951. if (arrow) {
  952. startupSource.add("(() => {\n");
  953. footer = "\n})();\n\n";
  954. } else {
  955. startupSource.add("!function() {\n");
  956. footer = "\n}();\n";
  957. }
  958. if (innerStrict) startupSource.add('"use strict";\n');
  959. } else {
  960. footer = "\n";
  961. }
  962. if (exports) {
  963. if (m !== lastInlinedModule) {
  964. startupSource.add(`var ${m.exportsArgument} = {};\n`);
  965. } else if (m.exportsArgument !== RuntimeGlobals.exports) {
  966. startupSource.add(
  967. `var ${m.exportsArgument} = ${RuntimeGlobals.exports};\n`
  968. );
  969. }
  970. }
  971. startupSource.add(renderedModule);
  972. startupSource.add(footer);
  973. }
  974. }
  975. if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) {
  976. startupSource.add(
  977. `${RuntimeGlobals.exports} = ${RuntimeGlobals.onChunksLoaded}(${RuntimeGlobals.exports});\n`
  978. );
  979. }
  980. source.add(
  981. hooks.renderStartup.call(startupSource, lastInlinedModule, {
  982. ...renderContext,
  983. inlined: true,
  984. inlinedInIIFE
  985. })
  986. );
  987. if (bootstrap.afterStartup.length > 0) {
  988. const afterStartup = `${Template.asString(bootstrap.afterStartup)}\n`;
  989. source.add(
  990. new PrefixSource(
  991. prefix,
  992. useSourceMap
  993. ? new OriginalSource(afterStartup, "webpack/after-startup")
  994. : new RawSource(afterStartup)
  995. )
  996. );
  997. }
  998. } else {
  999. const lastEntryModule =
  1000. /** @type {Module} */
  1001. (last(chunkGraph.getChunkEntryModulesIterable(chunk)));
  1002. /** @type {(content: string[], name: string) => Source} */
  1003. const toSource = useSourceMap
  1004. ? (content, name) =>
  1005. new OriginalSource(Template.asString(content), name)
  1006. : (content) => new RawSource(Template.asString(content));
  1007. source.add(
  1008. new PrefixSource(
  1009. prefix,
  1010. new ConcatSource(
  1011. toSource(bootstrap.beforeStartup, "webpack/before-startup"),
  1012. "\n",
  1013. hooks.renderStartup.call(
  1014. toSource([...bootstrap.startup, ""], "webpack/startup"),
  1015. lastEntryModule,
  1016. {
  1017. ...renderContext,
  1018. inlined: false
  1019. }
  1020. ),
  1021. toSource(bootstrap.afterStartup, "webpack/after-startup"),
  1022. "\n"
  1023. )
  1024. )
  1025. );
  1026. }
  1027. if (
  1028. hasEntryModules &&
  1029. runtimeRequirements.has(RuntimeGlobals.returnExportsFromRuntime)
  1030. ) {
  1031. source.add(`${prefix}return ${RuntimeGlobals.exports};\n`);
  1032. }
  1033. if (iife) {
  1034. source.add("/******/ })()\n");
  1035. }
  1036. /** @type {Source} */
  1037. let finalSource = tryRunOrWebpackError(
  1038. () => hooks.renderMain.call(source, renderContext),
  1039. "JavascriptModulesPlugin.getCompilationHooks().renderMain"
  1040. );
  1041. if (!finalSource) {
  1042. throw new Error(
  1043. "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderMain plugins should return something"
  1044. );
  1045. }
  1046. finalSource = tryRunOrWebpackError(
  1047. () => hooks.renderContent.call(finalSource, renderContext),
  1048. "JavascriptModulesPlugin.getCompilationHooks().renderContent"
  1049. );
  1050. if (!finalSource) {
  1051. throw new Error(
  1052. "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something"
  1053. );
  1054. }
  1055. finalSource = InitFragment.addToSource(
  1056. finalSource,
  1057. chunkRenderContext.chunkInitFragments,
  1058. chunkRenderContext
  1059. );
  1060. finalSource = tryRunOrWebpackError(
  1061. () => hooks.render.call(finalSource, renderContext),
  1062. "JavascriptModulesPlugin.getCompilationHooks().render"
  1063. );
  1064. if (!finalSource) {
  1065. throw new Error(
  1066. "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something"
  1067. );
  1068. }
  1069. chunk.rendered = true;
  1070. return iife ? new ConcatSource(finalSource, ";") : finalSource;
  1071. }
  1072. /**
  1073. * @param {Hash} hash the hash to be updated
  1074. * @param {RenderBootstrapContext} renderContext options object
  1075. * @param {CompilationHooks} hooks hooks
  1076. */
  1077. updateHashWithBootstrap(hash, renderContext, hooks) {
  1078. const bootstrap = this.renderBootstrap(renderContext, hooks);
  1079. for (const _k of Object.keys(bootstrap)) {
  1080. const key = /** @type {keyof Bootstrap} */ (_k);
  1081. hash.update(key);
  1082. if (Array.isArray(bootstrap[key])) {
  1083. for (const line of bootstrap[key]) {
  1084. hash.update(line);
  1085. }
  1086. } else {
  1087. hash.update(JSON.stringify(bootstrap[key]));
  1088. }
  1089. }
  1090. }
  1091. /**
  1092. * @param {RenderBootstrapContext} renderContext options object
  1093. * @param {CompilationHooks} hooks hooks
  1094. * @returns {Bootstrap} the generated source of the bootstrap code
  1095. */
  1096. renderBootstrap(renderContext, hooks) {
  1097. const {
  1098. chunkGraph,
  1099. codeGenerationResults,
  1100. moduleGraph,
  1101. chunk,
  1102. runtimeTemplate
  1103. } = renderContext;
  1104. const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk);
  1105. const requireFunction = runtimeRequirements.has(RuntimeGlobals.require);
  1106. const moduleCache = runtimeRequirements.has(RuntimeGlobals.moduleCache);
  1107. const moduleFactories = runtimeRequirements.has(
  1108. RuntimeGlobals.moduleFactories
  1109. );
  1110. const moduleUsed = runtimeRequirements.has(RuntimeGlobals.module);
  1111. const requireScopeUsed = runtimeRequirements.has(
  1112. RuntimeGlobals.requireScope
  1113. );
  1114. const interceptModuleExecution = runtimeRequirements.has(
  1115. RuntimeGlobals.interceptModuleExecution
  1116. );
  1117. const useRequire =
  1118. requireFunction || interceptModuleExecution || moduleUsed;
  1119. /**
  1120. * @type {{startup: string[], beforeStartup: string[], header: string[], afterStartup: string[], allowInlineStartup: boolean}}
  1121. */
  1122. const result = {
  1123. header: [],
  1124. beforeStartup: [],
  1125. startup: [],
  1126. afterStartup: [],
  1127. allowInlineStartup: true
  1128. };
  1129. const { header: buf, startup, beforeStartup, afterStartup } = result;
  1130. if (result.allowInlineStartup && moduleFactories) {
  1131. startup.push(
  1132. "// module factories are used so entry inlining is disabled"
  1133. );
  1134. result.allowInlineStartup = false;
  1135. }
  1136. if (result.allowInlineStartup && moduleCache) {
  1137. startup.push("// module cache are used so entry inlining is disabled");
  1138. result.allowInlineStartup = false;
  1139. }
  1140. if (result.allowInlineStartup && interceptModuleExecution) {
  1141. startup.push(
  1142. "// module execution is intercepted so entry inlining is disabled"
  1143. );
  1144. result.allowInlineStartup = false;
  1145. }
  1146. if (useRequire || moduleCache) {
  1147. buf.push("// The module cache");
  1148. buf.push("var __webpack_module_cache__ = {};");
  1149. buf.push("");
  1150. }
  1151. if (runtimeRequirements.has(RuntimeGlobals.makeDeferredNamespaceObject)) {
  1152. // in order to optimize of DeferredNamespaceObject, we remove all proxy handlers after the module initialize
  1153. // (see MakeDeferredNamespaceObjectRuntimeModule)
  1154. // This requires all deferred imports to a module can get the module export object before the module
  1155. // is evaluated.
  1156. buf.push("// The deferred module cache");
  1157. buf.push("var __webpack_module_deferred_exports__ = {};");
  1158. buf.push("");
  1159. }
  1160. if (useRequire) {
  1161. buf.push("// The require function");
  1162. buf.push(`function ${RuntimeGlobals.require}(moduleId) {`);
  1163. buf.push(Template.indent(this.renderRequire(renderContext, hooks)));
  1164. buf.push("}");
  1165. buf.push("");
  1166. } else if (runtimeRequirements.has(RuntimeGlobals.requireScope)) {
  1167. buf.push("// The require scope");
  1168. buf.push(`var ${RuntimeGlobals.require} = {};`);
  1169. buf.push("");
  1170. }
  1171. if (
  1172. moduleFactories ||
  1173. runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly)
  1174. ) {
  1175. buf.push("// expose the modules object (__webpack_modules__)");
  1176. buf.push(`${RuntimeGlobals.moduleFactories} = __webpack_modules__;`);
  1177. buf.push("");
  1178. }
  1179. if (moduleCache) {
  1180. buf.push("// expose the module cache");
  1181. buf.push(`${RuntimeGlobals.moduleCache} = __webpack_module_cache__;`);
  1182. buf.push("");
  1183. }
  1184. if (interceptModuleExecution) {
  1185. buf.push("// expose the module execution interceptor");
  1186. buf.push(`${RuntimeGlobals.interceptModuleExecution} = [];`);
  1187. buf.push("");
  1188. }
  1189. if (!runtimeRequirements.has(RuntimeGlobals.startupNoDefault)) {
  1190. if (chunkGraph.getNumberOfEntryModules(chunk) > 0) {
  1191. /** @type {string[]} */
  1192. const buf2 = [];
  1193. const runtimeRequirements =
  1194. chunkGraph.getTreeRuntimeRequirements(chunk);
  1195. buf2.push("// Load entry module and return exports");
  1196. let i = chunkGraph.getNumberOfEntryModules(chunk);
  1197. for (const [
  1198. entryModule,
  1199. entrypoint
  1200. ] of chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk)) {
  1201. if (!chunkGraph.getModuleSourceTypes(entryModule).has("javascript")) {
  1202. i--;
  1203. continue;
  1204. }
  1205. const chunks =
  1206. /** @type {Entrypoint} */
  1207. (entrypoint).chunks.filter((c) => c !== chunk);
  1208. if (result.allowInlineStartup && chunks.length > 0) {
  1209. buf2.push(
  1210. "// This entry module depends on other loaded chunks and execution need to be delayed"
  1211. );
  1212. result.allowInlineStartup = false;
  1213. }
  1214. if (
  1215. result.allowInlineStartup &&
  1216. someInIterable(
  1217. moduleGraph.getIncomingConnectionsByOriginModule(entryModule),
  1218. ([originModule, connections]) =>
  1219. originModule &&
  1220. connections.some((c) => c.isTargetActive(chunk.runtime)) &&
  1221. someInIterable(
  1222. chunkGraph.getModuleRuntimes(originModule),
  1223. (runtime) =>
  1224. intersectRuntime(runtime, chunk.runtime) !== undefined
  1225. )
  1226. )
  1227. ) {
  1228. buf2.push(
  1229. "// This entry module is referenced by other modules so it can't be inlined"
  1230. );
  1231. result.allowInlineStartup = false;
  1232. }
  1233. let data;
  1234. if (codeGenerationResults.has(entryModule, chunk.runtime)) {
  1235. const result = codeGenerationResults.get(
  1236. entryModule,
  1237. chunk.runtime
  1238. );
  1239. data = result.data;
  1240. }
  1241. if (
  1242. result.allowInlineStartup &&
  1243. (!data || !data.get("topLevelDeclarations")) &&
  1244. (!entryModule.buildInfo ||
  1245. !entryModule.buildInfo.topLevelDeclarations)
  1246. ) {
  1247. buf2.push(
  1248. "// This entry module doesn't tell about it's top-level declarations so it can't be inlined"
  1249. );
  1250. result.allowInlineStartup = false;
  1251. }
  1252. if (result.allowInlineStartup) {
  1253. const bailout = hooks.inlineInRuntimeBailout.call(
  1254. entryModule,
  1255. renderContext
  1256. );
  1257. if (bailout !== undefined) {
  1258. buf2.push(
  1259. `// This entry module can't be inlined because ${bailout}`
  1260. );
  1261. result.allowInlineStartup = false;
  1262. }
  1263. }
  1264. i--;
  1265. const moduleId = chunkGraph.getModuleId(entryModule);
  1266. const entryRuntimeRequirements =
  1267. chunkGraph.getModuleRuntimeRequirements(entryModule, chunk.runtime);
  1268. let moduleIdExpr = JSON.stringify(moduleId);
  1269. if (runtimeRequirements.has(RuntimeGlobals.entryModuleId)) {
  1270. moduleIdExpr = `${RuntimeGlobals.entryModuleId} = ${moduleIdExpr}`;
  1271. }
  1272. if (
  1273. result.allowInlineStartup &&
  1274. entryRuntimeRequirements.has(RuntimeGlobals.module)
  1275. ) {
  1276. result.allowInlineStartup = false;
  1277. buf2.push(
  1278. "// This entry module used 'module' so it can't be inlined"
  1279. );
  1280. }
  1281. if (chunks.length > 0) {
  1282. buf2.push(
  1283. `${i === 0 ? `var ${RuntimeGlobals.exports} = ` : ""}${
  1284. RuntimeGlobals.onChunksLoaded
  1285. }(undefined, ${JSON.stringify(
  1286. chunks.map((c) => c.id)
  1287. )}, ${runtimeTemplate.returningFunction(
  1288. `${RuntimeGlobals.require}(${moduleIdExpr})`
  1289. )})`
  1290. );
  1291. } else if (useRequire) {
  1292. buf2.push(
  1293. `${i === 0 ? `var ${RuntimeGlobals.exports} = ` : ""}${
  1294. RuntimeGlobals.require
  1295. }(${moduleIdExpr});`
  1296. );
  1297. } else {
  1298. if (i === 0) buf2.push(`var ${RuntimeGlobals.exports} = {};`);
  1299. if (requireScopeUsed) {
  1300. buf2.push(
  1301. `__webpack_modules__[${moduleIdExpr}](0, ${
  1302. i === 0 ? RuntimeGlobals.exports : "{}"
  1303. }, ${RuntimeGlobals.require});`
  1304. );
  1305. } else if (entryRuntimeRequirements.has(RuntimeGlobals.exports)) {
  1306. buf2.push(
  1307. `__webpack_modules__[${moduleIdExpr}](0, ${
  1308. i === 0 ? RuntimeGlobals.exports : "{}"
  1309. });`
  1310. );
  1311. } else {
  1312. buf2.push(`__webpack_modules__[${moduleIdExpr}]();`);
  1313. }
  1314. }
  1315. }
  1316. if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) {
  1317. buf2.push(
  1318. `${RuntimeGlobals.exports} = ${RuntimeGlobals.onChunksLoaded}(${RuntimeGlobals.exports});`
  1319. );
  1320. }
  1321. if (
  1322. runtimeRequirements.has(RuntimeGlobals.startup) ||
  1323. (runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) &&
  1324. runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter))
  1325. ) {
  1326. result.allowInlineStartup = false;
  1327. buf.push("// the startup function");
  1328. buf.push(
  1329. `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction("", [
  1330. ...buf2,
  1331. `return ${RuntimeGlobals.exports};`
  1332. ])};`
  1333. );
  1334. buf.push("");
  1335. startup.push("// run startup");
  1336. startup.push(
  1337. `var ${RuntimeGlobals.exports} = ${RuntimeGlobals.startup}();`
  1338. );
  1339. } else if (runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore)) {
  1340. buf.push("// the startup function");
  1341. buf.push(
  1342. `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};`
  1343. );
  1344. beforeStartup.push("// run runtime startup");
  1345. beforeStartup.push(`${RuntimeGlobals.startup}();`);
  1346. startup.push("// startup");
  1347. startup.push(Template.asString(buf2));
  1348. } else if (runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)) {
  1349. buf.push("// the startup function");
  1350. buf.push(
  1351. `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};`
  1352. );
  1353. startup.push("// startup");
  1354. startup.push(Template.asString(buf2));
  1355. afterStartup.push("// run runtime startup");
  1356. afterStartup.push(`${RuntimeGlobals.startup}();`);
  1357. } else {
  1358. startup.push("// startup");
  1359. startup.push(Template.asString(buf2));
  1360. }
  1361. } else if (
  1362. runtimeRequirements.has(RuntimeGlobals.startup) ||
  1363. runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) ||
  1364. runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)
  1365. ) {
  1366. buf.push(
  1367. "// the startup function",
  1368. "// It's empty as no entry modules are in this chunk",
  1369. `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};`,
  1370. ""
  1371. );
  1372. }
  1373. } else if (
  1374. runtimeRequirements.has(RuntimeGlobals.startup) ||
  1375. runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) ||
  1376. runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)
  1377. ) {
  1378. result.allowInlineStartup = false;
  1379. buf.push(
  1380. "// the startup function",
  1381. "// It's empty as some runtime module handles the default behavior",
  1382. `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};`
  1383. );
  1384. startup.push("// run startup");
  1385. startup.push(
  1386. `var ${RuntimeGlobals.exports} = ${RuntimeGlobals.startup}();`
  1387. );
  1388. }
  1389. return result;
  1390. }
  1391. /**
  1392. * @param {RenderBootstrapContext} renderContext options object
  1393. * @param {CompilationHooks} hooks hooks
  1394. * @returns {string} the generated source of the require function
  1395. */
  1396. renderRequire(renderContext, hooks) {
  1397. const {
  1398. chunk,
  1399. chunkGraph,
  1400. runtimeTemplate: { outputOptions }
  1401. } = renderContext;
  1402. const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk);
  1403. const moduleExecution = runtimeRequirements.has(
  1404. RuntimeGlobals.interceptModuleExecution
  1405. )
  1406. ? Template.asString([
  1407. `var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: ${RuntimeGlobals.require} };`,
  1408. `${RuntimeGlobals.interceptModuleExecution}.forEach(function(handler) { handler(execOptions); });`,
  1409. "module = execOptions.module;",
  1410. "execOptions.factory.call(module.exports, module, module.exports, execOptions.require);"
  1411. ])
  1412. : runtimeRequirements.has(RuntimeGlobals.thisAsExports)
  1413. ? Template.asString([
  1414. `__webpack_modules__[moduleId].call(module.exports, module, module.exports, ${RuntimeGlobals.require});`
  1415. ])
  1416. : Template.asString([
  1417. `__webpack_modules__[moduleId](module, module.exports, ${RuntimeGlobals.require});`
  1418. ]);
  1419. const needModuleId = runtimeRequirements.has(RuntimeGlobals.moduleId);
  1420. const needModuleLoaded = runtimeRequirements.has(
  1421. RuntimeGlobals.moduleLoaded
  1422. );
  1423. const needModuleDefer = runtimeRequirements.has(
  1424. RuntimeGlobals.makeDeferredNamespaceObject
  1425. );
  1426. const content = Template.asString([
  1427. "// Check if module is in cache",
  1428. "var cachedModule = __webpack_module_cache__[moduleId];",
  1429. "if (cachedModule !== undefined) {",
  1430. outputOptions.strictModuleErrorHandling
  1431. ? Template.indent([
  1432. "if (cachedModule.error !== undefined) throw cachedModule.error;",
  1433. "return cachedModule.exports;"
  1434. ])
  1435. : Template.indent("return cachedModule.exports;"),
  1436. "}",
  1437. "// Create a new module (and put it into the cache)",
  1438. "var module = __webpack_module_cache__[moduleId] = {",
  1439. Template.indent([
  1440. needModuleId ? "id: moduleId," : "// no module.id needed",
  1441. needModuleLoaded ? "loaded: false," : "// no module.loaded needed",
  1442. needModuleDefer
  1443. ? "exports: __webpack_module_deferred_exports__[moduleId] || {}"
  1444. : "exports: {}"
  1445. ]),
  1446. "};",
  1447. "",
  1448. outputOptions.strictModuleExceptionHandling
  1449. ? Template.asString([
  1450. "// Execute the module function",
  1451. "var threw = true;",
  1452. "try {",
  1453. Template.indent([
  1454. moduleExecution,
  1455. "threw = false;",
  1456. ...(needModuleDefer
  1457. ? ["delete __webpack_module_deferred_exports__[moduleId];"]
  1458. : [])
  1459. ]),
  1460. "} finally {",
  1461. Template.indent([
  1462. "if(threw) delete __webpack_module_cache__[moduleId];"
  1463. ]),
  1464. "}"
  1465. ])
  1466. : outputOptions.strictModuleErrorHandling
  1467. ? Template.asString([
  1468. "// Execute the module function",
  1469. "try {",
  1470. Template.indent(
  1471. needModuleDefer
  1472. ? [
  1473. moduleExecution,
  1474. "delete __webpack_module_deferred_exports__[moduleId];"
  1475. ]
  1476. : moduleExecution
  1477. ),
  1478. "} catch(e) {",
  1479. Template.indent(["module.error = e;", "throw e;"]),
  1480. "}"
  1481. ])
  1482. : Template.asString([
  1483. "// Execute the module function",
  1484. moduleExecution,
  1485. ...(needModuleDefer
  1486. ? [
  1487. "// delete __webpack_module_deferred_exports__[module];",
  1488. "// skipped because strictModuleErrorHandling is not enabled."
  1489. ]
  1490. : [])
  1491. ]),
  1492. needModuleLoaded
  1493. ? Template.asString([
  1494. "",
  1495. "// Flag the module as loaded",
  1496. `${RuntimeGlobals.moduleLoaded} = true;`,
  1497. ""
  1498. ])
  1499. : "",
  1500. "// Return the exports of the module",
  1501. "return module.exports;"
  1502. ]);
  1503. return tryRunOrWebpackError(
  1504. () => hooks.renderRequire.call(content, renderContext),
  1505. "JavascriptModulesPlugin.getCompilationHooks().renderRequire"
  1506. );
  1507. }
  1508. /**
  1509. * @param {Module[]} allModules allModules
  1510. * @param {MainRenderContext} renderContext renderContext
  1511. * @param {Set<Module>} inlinedModules inlinedModules
  1512. * @param {ChunkRenderContext} chunkRenderContext chunkRenderContext
  1513. * @param {CompilationHooks} hooks hooks
  1514. * @param {boolean | undefined} allStrict allStrict
  1515. * @param {boolean} hasChunkModules hasChunkModules
  1516. * @returns {Map<Module, Source> | false} renamed inlined modules
  1517. */
  1518. getRenamedInlineModule(
  1519. allModules,
  1520. renderContext,
  1521. inlinedModules,
  1522. chunkRenderContext,
  1523. hooks,
  1524. allStrict,
  1525. hasChunkModules
  1526. ) {
  1527. const innerStrict =
  1528. !allStrict &&
  1529. allModules.every((m) => /** @type {BuildInfo} */ (m.buildInfo).strict);
  1530. const isMultipleEntries = inlinedModules.size > 1;
  1531. const singleEntryWithModules = inlinedModules.size === 1 && hasChunkModules;
  1532. // TODO:
  1533. // This step is before the IIFE reason calculation. Ideally, it should only be executed when this function can optimize the
  1534. // IIFE reason. Otherwise, it should directly return false. There are four reasons now, we have skipped two already, the left
  1535. // one is 'it uses a non-standard name for the exports'.
  1536. if (isMultipleEntries || innerStrict || !singleEntryWithModules) {
  1537. return false;
  1538. }
  1539. /** @type {Map<Module, Source>} */
  1540. const renamedInlinedModules = new Map();
  1541. const { runtimeTemplate } = renderContext;
  1542. /** @typedef {{ source: Source, module: Module, ast: Program, variables: Set<Variable>, through: Set<Reference>, usedInNonInlined: Set<Variable>, moduleScope: Scope }} Info */
  1543. /** @type {Map<Module, Info>} */
  1544. const inlinedModulesToInfo = new Map();
  1545. /** @type {Set<string>} */
  1546. const nonInlinedModuleThroughIdentifiers = new Set();
  1547. /** @type {Map<Module, Source>} */
  1548. for (const m of allModules) {
  1549. const isInlinedModule = inlinedModules && inlinedModules.has(m);
  1550. const moduleSource = this.renderModule(
  1551. m,
  1552. {
  1553. ...chunkRenderContext,
  1554. factory: !isInlinedModule,
  1555. inlinedInIIFE: false
  1556. },
  1557. hooks
  1558. );
  1559. if (!moduleSource) continue;
  1560. const code = /** @type {string} */ (moduleSource.source());
  1561. const ast = JavascriptParser._parse(code, {
  1562. sourceType: "auto"
  1563. });
  1564. const scopeManager = eslintScope.analyze(ast, {
  1565. ecmaVersion: 6,
  1566. sourceType: "module",
  1567. optimistic: true,
  1568. ignoreEval: true
  1569. });
  1570. const globalScope = /** @type {Scope} */ (scopeManager.acquire(ast));
  1571. if (inlinedModules && inlinedModules.has(m)) {
  1572. const moduleScope = globalScope.childScopes[0];
  1573. inlinedModulesToInfo.set(m, {
  1574. source: moduleSource,
  1575. ast,
  1576. module: m,
  1577. variables: new Set(moduleScope.variables),
  1578. through: new Set(moduleScope.through),
  1579. usedInNonInlined: new Set(),
  1580. moduleScope
  1581. });
  1582. } else {
  1583. for (const ref of globalScope.through) {
  1584. nonInlinedModuleThroughIdentifiers.add(ref.identifier.name);
  1585. }
  1586. }
  1587. }
  1588. for (const [, { variables, usedInNonInlined }] of inlinedModulesToInfo) {
  1589. for (const variable of variables) {
  1590. if (
  1591. nonInlinedModuleThroughIdentifiers.has(variable.name) ||
  1592. RESERVED_NAMES.has(variable.name)
  1593. ) {
  1594. usedInNonInlined.add(variable);
  1595. }
  1596. }
  1597. }
  1598. for (const [m, moduleInfo] of inlinedModulesToInfo) {
  1599. const { ast, source: _source, usedInNonInlined } = moduleInfo;
  1600. const source = new ReplaceSource(_source);
  1601. if (usedInNonInlined.size === 0) {
  1602. renamedInlinedModules.set(m, source);
  1603. continue;
  1604. }
  1605. const info = /** @type {Info} */ (inlinedModulesToInfo.get(m));
  1606. const allUsedNames = new Set(
  1607. Array.from(info.through, (v) => v.identifier.name)
  1608. );
  1609. for (const variable of usedInNonInlined) {
  1610. allUsedNames.add(variable.name);
  1611. }
  1612. for (const variable of info.variables) {
  1613. const usedNamesInScopeInfo = new Map();
  1614. const ignoredScopes = new Set();
  1615. const name = variable.name;
  1616. const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo(
  1617. usedNamesInScopeInfo,
  1618. info.module.identifier(),
  1619. name
  1620. );
  1621. if (allUsedNames.has(name) || usedNames.has(name)) {
  1622. const references = getAllReferences(variable);
  1623. const allIdentifiers = new Set([
  1624. ...references.map((r) => r.identifier),
  1625. ...variable.identifiers
  1626. ]);
  1627. for (const ref of references) {
  1628. addScopeSymbols(
  1629. ref.from,
  1630. usedNames,
  1631. alreadyCheckedScopes,
  1632. ignoredScopes
  1633. );
  1634. }
  1635. const newName = findNewName(
  1636. variable.name,
  1637. allUsedNames,
  1638. usedNames,
  1639. m.readableIdentifier(runtimeTemplate.requestShortener)
  1640. );
  1641. allUsedNames.add(newName);
  1642. for (const identifier of allIdentifiers) {
  1643. const r = /** @type {Range} */ (identifier.range);
  1644. const path = getPathInAst(ast, identifier);
  1645. if (path && path.length > 1) {
  1646. const maybeProperty =
  1647. path[1].type === "AssignmentPattern" && path[1].left === path[0]
  1648. ? path[2]
  1649. : path[1];
  1650. if (
  1651. maybeProperty.type === "Property" &&
  1652. maybeProperty.shorthand
  1653. ) {
  1654. source.insert(r[1], `: ${newName}`);
  1655. continue;
  1656. }
  1657. }
  1658. source.replace(r[0], r[1] - 1, newName);
  1659. }
  1660. }
  1661. allUsedNames.add(name);
  1662. }
  1663. renamedInlinedModules.set(m, source);
  1664. }
  1665. return renamedInlinedModules;
  1666. }
  1667. }
  1668. module.exports = JavascriptModulesPlugin;
  1669. module.exports.chunkHasJs = chunkHasJs;