JavascriptModulesPlugin.js 53 KB

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