RuntimeTemplate.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const InitFragment = require("./InitFragment");
  7. const RuntimeGlobals = require("./RuntimeGlobals");
  8. const Template = require("./Template");
  9. const {
  10. getOutgoingAsyncModules
  11. } = require("./async-modules/AsyncModuleHelpers");
  12. const { ImportPhaseUtils } = require("./dependencies/ImportPhase");
  13. const {
  14. getMakeDeferredNamespaceModeFromExportsType,
  15. getOptimizedDeferredModule
  16. } = require("./runtime/MakeDeferredNamespaceObjectRuntime");
  17. const { equals } = require("./util/ArrayHelpers");
  18. const compileBooleanMatcher = require("./util/compileBooleanMatcher");
  19. const memoize = require("./util/memoize");
  20. const { propertyAccess } = require("./util/property");
  21. const { forEachRuntime, subtractRuntime } = require("./util/runtime");
  22. const getHarmonyImportDependency = memoize(() =>
  23. require("./dependencies/HarmonyImportDependency")
  24. );
  25. const getImportDependency = memoize(() =>
  26. require("./dependencies/ImportDependency")
  27. );
  28. /** @typedef {import("./config/defaults").OutputNormalizedWithDefaults} OutputOptions */
  29. /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
  30. /** @typedef {import("./Chunk")} Chunk */
  31. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  32. /** @typedef {import("./Compilation")} Compilation */
  33. /** @typedef {import("./Dependency")} Dependency */
  34. /** @typedef {import("./Module")} Module */
  35. /** @typedef {import("./Module").BuildMeta} BuildMeta */
  36. /** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
  37. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  38. /** @typedef {import("./RequestShortener")} RequestShortener */
  39. /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
  40. /** @typedef {import("./dependencies/ImportPhase").ImportPhaseType} ImportPhaseType */
  41. /** @typedef {import("./NormalModuleFactory").ModuleDependency} ModuleDependency */
  42. /**
  43. * No module id error message.
  44. * @param {Module} module the module
  45. * @param {ChunkGraph} chunkGraph the chunk graph
  46. * @returns {string} error message
  47. */
  48. const noModuleIdErrorMessage = (
  49. module,
  50. chunkGraph
  51. ) => `Module ${module.identifier()} has no id assigned.
  52. This should not happen.
  53. It's in these chunks: ${
  54. Array.from(
  55. chunkGraph.getModuleChunksIterable(module),
  56. (c) => c.name || c.id || c.debugId
  57. ).join(", ") || "none"
  58. } (If module is in no chunk this indicates a bug in some chunk/module optimization logic)
  59. Module has these incoming connections: ${Array.from(
  60. chunkGraph.moduleGraph.getIncomingConnections(module),
  61. (connection) =>
  62. `\n - ${
  63. connection.originModule && connection.originModule.identifier()
  64. } ${connection.dependency && connection.dependency.type} ${
  65. (connection.explanations && [...connection.explanations].join(", ")) || ""
  66. }`
  67. ).join("")}`;
  68. /**
  69. * Gets global object.
  70. * @param {string | undefined} definition global object definition
  71. * @returns {string | undefined} save to use global object
  72. */
  73. function getGlobalObject(definition) {
  74. if (!definition) return definition;
  75. const trimmed = definition.trim();
  76. if (
  77. // identifier, we do not need real identifier regarding ECMAScript/Unicode
  78. /^[_\p{L}][_0-9\p{L}]*$/iu.test(trimmed) ||
  79. // iife
  80. // call expression
  81. // expression in parentheses
  82. /^(?:[_\p{L}][_0-9\p{L}]*)?\(.*\)$/iu.test(trimmed)
  83. ) {
  84. return trimmed;
  85. }
  86. return `Object(${trimmed})`;
  87. }
  88. class RuntimeTemplate {
  89. /**
  90. * Creates an instance of RuntimeTemplate.
  91. * @param {Compilation} compilation the compilation
  92. * @param {OutputOptions} outputOptions the compilation output options
  93. * @param {RequestShortener} requestShortener the request shortener
  94. */
  95. constructor(compilation, outputOptions, requestShortener) {
  96. this.compilation = compilation;
  97. this.outputOptions = /** @type {OutputOptions} */ (outputOptions || {});
  98. this.requestShortener = requestShortener;
  99. this.globalObject =
  100. /** @type {string} */
  101. (getGlobalObject(outputOptions.globalObject));
  102. this.contentHashReplacement = "X".repeat(outputOptions.hashDigestLength);
  103. }
  104. isIIFE() {
  105. return this.outputOptions.iife;
  106. }
  107. isModule() {
  108. return this.outputOptions.module;
  109. }
  110. isNeutralPlatform() {
  111. return (
  112. !this.compilation.compiler.platform.web &&
  113. !this.compilation.compiler.platform.node
  114. );
  115. }
  116. supportsConst() {
  117. return this.outputOptions.environment.const;
  118. }
  119. supportsMethodShorthand() {
  120. return this.outputOptions.environment.methodShorthand;
  121. }
  122. supportsArrowFunction() {
  123. return this.outputOptions.environment.arrowFunction;
  124. }
  125. supportsAsyncFunction() {
  126. return this.outputOptions.environment.asyncFunction;
  127. }
  128. supportsOptionalChaining() {
  129. return this.outputOptions.environment.optionalChaining;
  130. }
  131. supportsForOf() {
  132. return this.outputOptions.environment.forOf;
  133. }
  134. supportsDestructuring() {
  135. return this.outputOptions.environment.destructuring;
  136. }
  137. supportsBigIntLiteral() {
  138. return this.outputOptions.environment.bigIntLiteral;
  139. }
  140. supportsDynamicImport() {
  141. return this.outputOptions.environment.dynamicImport;
  142. }
  143. supportsEcmaScriptModuleSyntax() {
  144. return this.outputOptions.environment.module;
  145. }
  146. supportTemplateLiteral() {
  147. return this.outputOptions.environment.templateLiteral;
  148. }
  149. supportNodePrefixForCoreModules() {
  150. return this.outputOptions.environment.nodePrefixForCoreModules;
  151. }
  152. /**
  153. * Renders node prefix for core module.
  154. * @param {string} mod a module
  155. * @returns {string} a module with `node:` prefix when supported, otherwise an original name
  156. */
  157. renderNodePrefixForCoreModule(mod) {
  158. return this.outputOptions.environment.nodePrefixForCoreModules
  159. ? `"node:${mod}"`
  160. : `"${mod}"`;
  161. }
  162. /**
  163. * Renders return const when it is supported, otherwise var.
  164. * @returns {"const" | "var"} return `const` when it is supported, otherwise `var`
  165. */
  166. renderConst() {
  167. return this.supportsConst() ? "const" : "var";
  168. }
  169. /**
  170. * Returning function.
  171. * @param {string} returnValue return value
  172. * @param {string} args arguments
  173. * @returns {string} returning function
  174. */
  175. returningFunction(returnValue, args = "") {
  176. return this.supportsArrowFunction()
  177. ? `(${args}) => (${returnValue})`
  178. : `function(${args}) { return ${returnValue}; }`;
  179. }
  180. /**
  181. * Returns basic function.
  182. * @param {string} args arguments
  183. * @param {string | string[]} body body
  184. * @returns {string} basic function
  185. */
  186. basicFunction(args, body) {
  187. return this.supportsArrowFunction()
  188. ? `(${args}) => {\n${Template.indent(body)}\n}`
  189. : `function(${args}) {\n${Template.indent(body)}\n}`;
  190. }
  191. /**
  192. * Returns result expression.
  193. * @param {(string | { expr: string })[]} args args
  194. * @returns {string} result expression
  195. */
  196. concatenation(...args) {
  197. const len = args.length;
  198. if (len === 2) return this._es5Concatenation(args);
  199. if (len === 0) return '""';
  200. if (len === 1) {
  201. return typeof args[0] === "string"
  202. ? JSON.stringify(args[0])
  203. : `"" + ${args[0].expr}`;
  204. }
  205. if (!this.supportTemplateLiteral()) return this._es5Concatenation(args);
  206. // cost comparison between template literal and concatenation:
  207. // both need equal surroundings: `xxx` vs "xxx"
  208. // template literal has constant cost of 3 chars for each expression
  209. // es5 concatenation has cost of 3 + n chars for n expressions in row
  210. // when a es5 concatenation ends with an expression it reduces cost by 3
  211. // when a es5 concatenation starts with an single expression it reduces cost by 3
  212. // e. g. `${a}${b}${c}` (3*3 = 9) is longer than ""+a+b+c ((3+3)-3 = 3)
  213. // e. g. `x${a}x${b}x${c}x` (3*3 = 9) is shorter than "x"+a+"x"+b+"x"+c+"x" (4+4+4 = 12)
  214. let templateCost = 0;
  215. let concatenationCost = 0;
  216. let lastWasExpr = false;
  217. for (const arg of args) {
  218. const isExpr = typeof arg !== "string";
  219. if (isExpr) {
  220. templateCost += 3;
  221. concatenationCost += lastWasExpr ? 1 : 4;
  222. }
  223. lastWasExpr = isExpr;
  224. }
  225. if (lastWasExpr) concatenationCost -= 3;
  226. if (typeof args[0] !== "string" && typeof args[1] === "string") {
  227. concatenationCost -= 3;
  228. }
  229. if (concatenationCost <= templateCost) return this._es5Concatenation(args);
  230. return `\`${args
  231. .map((arg) => (typeof arg === "string" ? arg : `\${${arg.expr}}`))
  232. .join("")}\``;
  233. }
  234. /**
  235. * Returns result expression.
  236. * @param {(string | { expr: string })[]} args args (len >= 2)
  237. * @returns {string} result expression
  238. * @private
  239. */
  240. _es5Concatenation(args) {
  241. const str = args
  242. .map((arg) => (typeof arg === "string" ? JSON.stringify(arg) : arg.expr))
  243. .join(" + ");
  244. // when the first two args are expression, we need to prepend "" + to force string
  245. // concatenation instead of number addition.
  246. return typeof args[0] !== "string" && typeof args[1] !== "string"
  247. ? `"" + ${str}`
  248. : str;
  249. }
  250. /**
  251. * Expression function.
  252. * @param {string} expression expression
  253. * @param {string} args arguments
  254. * @returns {string} expression function code
  255. */
  256. expressionFunction(expression, args = "") {
  257. return this.supportsArrowFunction()
  258. ? `(${args}) => (${expression})`
  259. : `function(${args}) { ${expression}; }`;
  260. }
  261. /**
  262. * Returns empty function code.
  263. * @returns {string} empty function code
  264. */
  265. emptyFunction() {
  266. return this.supportsArrowFunction() ? "x => {}" : "function() {}";
  267. }
  268. /**
  269. * Returns destructure array code.
  270. * @param {string[]} items items
  271. * @param {string} value value
  272. * @returns {string} destructure array code
  273. */
  274. destructureArray(items, value) {
  275. return this.supportsDestructuring()
  276. ? `var [${items.join(", ")}] = ${value};`
  277. : Template.asString(
  278. items.map((item, i) => `var ${item} = ${value}[${i}];`)
  279. );
  280. }
  281. /**
  282. * Destructure object.
  283. * @param {string[]} items items
  284. * @param {string} value value
  285. * @returns {string} destructure object code
  286. */
  287. destructureObject(items, value) {
  288. return this.supportsDestructuring()
  289. ? `var {${items.join(", ")}} = ${value};`
  290. : Template.asString(
  291. items.map(
  292. (item) => `var ${item} = ${value}${propertyAccess([item])};`
  293. )
  294. );
  295. }
  296. /**
  297. * Returns iIFE code.
  298. * @param {string} args arguments
  299. * @param {string} body body
  300. * @returns {string} IIFE code
  301. */
  302. iife(args, body) {
  303. return `(${this.basicFunction(args, body)})()`;
  304. }
  305. /**
  306. * Returns for each code.
  307. * @param {string} variable variable
  308. * @param {string} array array
  309. * @param {string | string[]} body body
  310. * @returns {string} for each code
  311. */
  312. forEach(variable, array, body) {
  313. return this.supportsForOf()
  314. ? `for(const ${variable} of ${array}) {\n${Template.indent(body)}\n}`
  315. : `${array}.forEach(function(${variable}) {\n${Template.indent(
  316. body
  317. )}\n});`;
  318. }
  319. /**
  320. * Returns comment.
  321. * @param {object} options Information content of the comment
  322. * @param {string=} options.request request string used originally
  323. * @param {(string | null)=} options.chunkName name of the chunk referenced
  324. * @param {string=} options.chunkReason reason information of the chunk
  325. * @param {string=} options.message additional message
  326. * @param {string=} options.exportName name of the export
  327. * @returns {string} comment
  328. */
  329. comment({ request, chunkName, chunkReason, message, exportName }) {
  330. /** @type {string} */
  331. let content;
  332. if (this.outputOptions.pathinfo) {
  333. content = [message, request, chunkName, chunkReason]
  334. .filter(Boolean)
  335. .map((item) => this.requestShortener.shorten(item))
  336. .join(" | ");
  337. } else {
  338. content = [message, chunkName, chunkReason]
  339. .filter(Boolean)
  340. .map((item) => this.requestShortener.shorten(item))
  341. .join(" | ");
  342. }
  343. if (!content) return "";
  344. if (this.outputOptions.pathinfo) {
  345. return `${Template.toComment(content)} `;
  346. }
  347. return `${Template.toNormalComment(content)} `;
  348. }
  349. /**
  350. * Throw missing module error block.
  351. * @param {object} options generation options
  352. * @param {string=} options.request request string used originally
  353. * @returns {string} generated error block
  354. */
  355. throwMissingModuleErrorBlock({ request }) {
  356. const err = `Cannot find module '${request}'`;
  357. return `var e = new Error(${JSON.stringify(
  358. err
  359. )}); e.code = 'MODULE_NOT_FOUND'; throw e;`;
  360. }
  361. /**
  362. * Throw missing module error function.
  363. * @param {object} options generation options
  364. * @param {string=} options.request request string used originally
  365. * @returns {string} generated error function
  366. */
  367. throwMissingModuleErrorFunction({ request }) {
  368. return `function webpackMissingModule() { ${this.throwMissingModuleErrorBlock(
  369. { request }
  370. )} }`;
  371. }
  372. /**
  373. * Returns generated error IIFE.
  374. * @param {object} options generation options
  375. * @param {string=} options.request request string used originally
  376. * @returns {string} generated error IIFE
  377. */
  378. missingModule({ request }) {
  379. return `Object(${this.throwMissingModuleErrorFunction({ request })}())`;
  380. }
  381. /**
  382. * Missing module statement.
  383. * @param {object} options generation options
  384. * @param {string=} options.request request string used originally
  385. * @returns {string} generated error statement
  386. */
  387. missingModuleStatement({ request }) {
  388. return `${this.missingModule({ request })};\n`;
  389. }
  390. /**
  391. * Missing module promise.
  392. * @param {object} options generation options
  393. * @param {string=} options.request request string used originally
  394. * @returns {string} generated error code
  395. */
  396. missingModulePromise({ request }) {
  397. return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({
  398. request
  399. })})`;
  400. }
  401. /**
  402. * Returns the code.
  403. * @param {object} options options object
  404. * @param {ChunkGraph} options.chunkGraph the chunk graph
  405. * @param {Module} options.module the module
  406. * @param {string=} options.request the request that should be printed as comment
  407. * @param {string=} options.idExpr expression to use as id expression
  408. * @param {"expression" | "promise" | "statements"} options.type which kind of code should be returned
  409. * @returns {string} the code
  410. */
  411. weakError({ module, chunkGraph, request, idExpr, type }) {
  412. const moduleId = chunkGraph.getModuleId(module);
  413. const errorMessage =
  414. moduleId === null
  415. ? JSON.stringify("Module is not available (weak dependency)")
  416. : idExpr
  417. ? `"Module '" + ${idExpr} + "' is not available (weak dependency)"`
  418. : JSON.stringify(
  419. `Module '${moduleId}' is not available (weak dependency)`
  420. );
  421. const comment = request ? `${Template.toNormalComment(request)} ` : "";
  422. const errorStatements = `var e = new Error(${errorMessage}); ${
  423. comment
  424. }e.code = 'MODULE_NOT_FOUND'; throw e;`;
  425. switch (type) {
  426. case "statements":
  427. return errorStatements;
  428. case "promise":
  429. return `Promise.resolve().then(${this.basicFunction(
  430. "",
  431. errorStatements
  432. )})`;
  433. case "expression":
  434. return this.iife("", errorStatements);
  435. }
  436. }
  437. /**
  438. * Returns the expression.
  439. * @param {object} options options object
  440. * @param {Module} options.module the module
  441. * @param {ChunkGraph} options.chunkGraph the chunk graph
  442. * @param {string=} options.request the request that should be printed as comment
  443. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  444. * @returns {string} the expression
  445. */
  446. moduleId({ module, chunkGraph, request, weak }) {
  447. if (!module) {
  448. return this.missingModule({
  449. request
  450. });
  451. }
  452. const moduleId = chunkGraph.getModuleId(module);
  453. if (moduleId === null) {
  454. if (weak) {
  455. return "null /* weak dependency, without id */";
  456. }
  457. throw new Error(
  458. `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage(
  459. module,
  460. chunkGraph
  461. )}`
  462. );
  463. }
  464. return `${this.comment({ request })}${JSON.stringify(moduleId)}`;
  465. }
  466. /**
  467. * Returns the expression.
  468. * @param {object} options options object
  469. * @param {Module | null} options.module the module
  470. * @param {ChunkGraph} options.chunkGraph the chunk graph
  471. * @param {string=} options.request the request that should be printed as comment
  472. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  473. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  474. * @returns {string} the expression
  475. */
  476. moduleRaw({ module, chunkGraph, request, weak, runtimeRequirements }) {
  477. if (!module) {
  478. return this.missingModule({
  479. request
  480. });
  481. }
  482. const moduleId = chunkGraph.getModuleId(module);
  483. if (moduleId === null) {
  484. if (weak) {
  485. // only weak referenced modules don't get an id
  486. // we can always emit an error emitting code here
  487. return this.weakError({
  488. module,
  489. chunkGraph,
  490. request,
  491. type: "expression"
  492. });
  493. }
  494. throw new Error(
  495. `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage(
  496. module,
  497. chunkGraph
  498. )}`
  499. );
  500. }
  501. runtimeRequirements.add(RuntimeGlobals.require);
  502. return `${RuntimeGlobals.require}(${this.moduleId({
  503. module,
  504. chunkGraph,
  505. request,
  506. weak
  507. })})`;
  508. }
  509. /**
  510. * Returns the expression.
  511. * @param {object} options options object
  512. * @param {Module | null} options.module the module
  513. * @param {ChunkGraph} options.chunkGraph the chunk graph
  514. * @param {string} options.request the request that should be printed as comment
  515. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  516. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  517. * @returns {string} the expression
  518. */
  519. moduleExports({ module, chunkGraph, request, weak, runtimeRequirements }) {
  520. return this.moduleRaw({
  521. module,
  522. chunkGraph,
  523. request,
  524. weak,
  525. runtimeRequirements
  526. });
  527. }
  528. /**
  529. * Returns the expression.
  530. * @param {object} options options object
  531. * @param {Module} options.module the module
  532. * @param {ChunkGraph} options.chunkGraph the chunk graph
  533. * @param {string} options.request the request that should be printed as comment
  534. * @param {boolean=} options.strict if the current module is in strict esm mode
  535. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  536. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  537. * @returns {string} the expression
  538. */
  539. moduleNamespace({
  540. module,
  541. chunkGraph,
  542. request,
  543. strict,
  544. weak,
  545. runtimeRequirements
  546. }) {
  547. if (!module) {
  548. return this.missingModule({
  549. request
  550. });
  551. }
  552. if (chunkGraph.getModuleId(module) === null) {
  553. if (weak) {
  554. // only weak referenced modules don't get an id
  555. // we can always emit an error emitting code here
  556. return this.weakError({
  557. module,
  558. chunkGraph,
  559. request,
  560. type: "expression"
  561. });
  562. }
  563. throw new Error(
  564. `RuntimeTemplate.moduleNamespace(): ${noModuleIdErrorMessage(
  565. module,
  566. chunkGraph
  567. )}`
  568. );
  569. }
  570. const moduleId = this.moduleId({
  571. module,
  572. chunkGraph,
  573. request,
  574. weak
  575. });
  576. const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict);
  577. switch (exportsType) {
  578. case "namespace":
  579. return this.moduleRaw({
  580. module,
  581. chunkGraph,
  582. request,
  583. weak,
  584. runtimeRequirements
  585. });
  586. case "default-with-named":
  587. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  588. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 3)`;
  589. case "default-only":
  590. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  591. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 1)`;
  592. case "dynamic":
  593. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  594. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 7)`;
  595. }
  596. }
  597. /**
  598. * Module namespace promise.
  599. * @param {object} options options object
  600. * @param {ChunkGraph} options.chunkGraph the chunk graph
  601. * @param {AsyncDependenciesBlock=} options.block the current dependencies block
  602. * @param {Module} options.module the module
  603. * @param {string} options.request the request that should be printed as comment
  604. * @param {string} options.message a message for the comment
  605. * @param {boolean=} options.strict if the current module is in strict esm mode
  606. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  607. * @param {Dependency} options.dependency dependency
  608. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  609. * @returns {string} the promise expression
  610. */
  611. moduleNamespacePromise({
  612. chunkGraph,
  613. block,
  614. module,
  615. request,
  616. message,
  617. strict,
  618. weak,
  619. dependency,
  620. runtimeRequirements
  621. }) {
  622. if (!module) {
  623. return this.missingModulePromise({
  624. request
  625. });
  626. }
  627. const moduleId = chunkGraph.getModuleId(module);
  628. if (moduleId === null) {
  629. if (weak) {
  630. // only weak referenced modules don't get an id
  631. // we can always emit an error emitting code here
  632. return this.weakError({
  633. module,
  634. chunkGraph,
  635. request,
  636. type: "promise"
  637. });
  638. }
  639. throw new Error(
  640. `RuntimeTemplate.moduleNamespacePromise(): ${noModuleIdErrorMessage(
  641. module,
  642. chunkGraph
  643. )}`
  644. );
  645. }
  646. const promise = this.blockPromise({
  647. chunkGraph,
  648. block,
  649. message,
  650. runtimeRequirements
  651. });
  652. /** @type {string} */
  653. let appending;
  654. let idExpr = JSON.stringify(chunkGraph.getModuleId(module));
  655. const comment = this.comment({
  656. request
  657. });
  658. let header = "";
  659. if (weak) {
  660. if (idExpr.length > 8) {
  661. // 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"'
  662. header += `var id = ${idExpr}; `;
  663. idExpr = "id";
  664. }
  665. runtimeRequirements.add(RuntimeGlobals.moduleFactories);
  666. header += `if(!${
  667. RuntimeGlobals.moduleFactories
  668. }[${idExpr}]) { ${this.weakError({
  669. module,
  670. chunkGraph,
  671. request,
  672. idExpr,
  673. type: "statements"
  674. })} } `;
  675. }
  676. const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict);
  677. const isModuleDeferred =
  678. (dependency instanceof getHarmonyImportDependency() ||
  679. dependency instanceof getImportDependency()) &&
  680. ImportPhaseUtils.isDefer(dependency.phase) &&
  681. !(/** @type {BuildMeta} */ (module.buildMeta).async);
  682. if (isModuleDeferred) {
  683. runtimeRequirements.add(RuntimeGlobals.makeDeferredNamespaceObject);
  684. let mode = getMakeDeferredNamespaceModeFromExportsType(exportsType);
  685. if (mode) mode = `${mode} | 16`;
  686. const asyncDeps = Array.from(
  687. getOutgoingAsyncModules(chunkGraph.moduleGraph, module),
  688. (m) => chunkGraph.getModuleId(m)
  689. ).filter((id) => id !== null);
  690. if (asyncDeps.length) {
  691. if (header) {
  692. appending = `.then(${this.basicFunction(
  693. "",
  694. `${header}return ${RuntimeGlobals.deferredModuleAsyncTransitiveDependencies}(${JSON.stringify(asyncDeps)});`
  695. )})`;
  696. } else {
  697. runtimeRequirements.add(RuntimeGlobals.require);
  698. appending = `.then(${this.returningFunction(`${RuntimeGlobals.deferredModuleAsyncTransitiveDependencies}(${JSON.stringify(asyncDeps)})`)})`;
  699. }
  700. appending += `.then(${RuntimeGlobals.makeDeferredNamespaceObject}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}, ${mode}))`;
  701. } else if (header) {
  702. appending = `.then(${this.basicFunction(
  703. "",
  704. `${header}return ${RuntimeGlobals.makeDeferredNamespaceObject}(${comment}${idExpr}, ${mode});`
  705. )})`;
  706. } else {
  707. runtimeRequirements.add(RuntimeGlobals.require);
  708. appending = `.then(${RuntimeGlobals.makeDeferredNamespaceObject}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}, ${mode}))`;
  709. }
  710. } else {
  711. let fakeType = 16;
  712. switch (exportsType) {
  713. case "namespace":
  714. if (header) {
  715. const rawModule = this.moduleRaw({
  716. module,
  717. chunkGraph,
  718. request,
  719. weak,
  720. runtimeRequirements
  721. });
  722. appending = `.then(${this.basicFunction(
  723. "",
  724. `${header}return ${rawModule};`
  725. )})`;
  726. } else {
  727. runtimeRequirements.add(RuntimeGlobals.require);
  728. appending = `.then(${RuntimeGlobals.require}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}))`;
  729. }
  730. break;
  731. case "dynamic":
  732. fakeType |= 4;
  733. /* fall through */
  734. case "default-with-named":
  735. fakeType |= 2;
  736. /* fall through */
  737. case "default-only":
  738. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  739. if (chunkGraph.moduleGraph.isAsync(module)) {
  740. if (header) {
  741. const rawModule = this.moduleRaw({
  742. module,
  743. chunkGraph,
  744. request,
  745. weak,
  746. runtimeRequirements
  747. });
  748. appending = `.then(${this.basicFunction(
  749. "",
  750. `${header}return ${rawModule};`
  751. )})`;
  752. } else {
  753. runtimeRequirements.add(RuntimeGlobals.require);
  754. appending = `.then(${RuntimeGlobals.require}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}))`;
  755. }
  756. appending += `.then(${this.returningFunction(
  757. `${RuntimeGlobals.createFakeNamespaceObject}(m, ${fakeType})`,
  758. "m"
  759. )})`;
  760. } else {
  761. fakeType |= 1;
  762. if (header) {
  763. const moduleIdExpr = this.moduleId({
  764. module,
  765. chunkGraph,
  766. request,
  767. weak
  768. });
  769. const returnExpression = `${RuntimeGlobals.createFakeNamespaceObject}(${moduleIdExpr}, ${fakeType})`;
  770. appending = `.then(${this.basicFunction(
  771. "",
  772. `${header}return ${returnExpression};`
  773. )})`;
  774. } else {
  775. appending = `.then(${RuntimeGlobals.createFakeNamespaceObject}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}, ${fakeType}))`;
  776. }
  777. }
  778. break;
  779. }
  780. }
  781. return `${promise || "Promise.resolve()"}${appending}`;
  782. }
  783. /**
  784. * Runtime condition expression.
  785. * @param {object} options options object
  786. * @param {ChunkGraph} options.chunkGraph the chunk graph
  787. * @param {RuntimeSpec=} options.runtime runtime for which this code will be generated
  788. * @param {RuntimeSpec | boolean=} options.runtimeCondition only execute the statement in some runtimes
  789. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  790. * @returns {string} expression
  791. */
  792. runtimeConditionExpression({
  793. chunkGraph,
  794. runtimeCondition,
  795. runtime,
  796. runtimeRequirements
  797. }) {
  798. if (runtimeCondition === undefined) return "true";
  799. if (typeof runtimeCondition === "boolean") return `${runtimeCondition}`;
  800. /** @type {Set<string>} */
  801. const positiveRuntimeIds = new Set();
  802. forEachRuntime(runtimeCondition, (runtime) =>
  803. positiveRuntimeIds.add(
  804. `${chunkGraph.getRuntimeId(/** @type {string} */ (runtime))}`
  805. )
  806. );
  807. /** @type {Set<string>} */
  808. const negativeRuntimeIds = new Set();
  809. forEachRuntime(subtractRuntime(runtime, runtimeCondition), (runtime) =>
  810. negativeRuntimeIds.add(
  811. `${chunkGraph.getRuntimeId(/** @type {string} */ (runtime))}`
  812. )
  813. );
  814. runtimeRequirements.add(RuntimeGlobals.runtimeId);
  815. return compileBooleanMatcher.fromLists(
  816. [...positiveRuntimeIds],
  817. [...negativeRuntimeIds]
  818. )(RuntimeGlobals.runtimeId);
  819. }
  820. /**
  821. * Returns the import statement and the compat statement.
  822. * @param {object} options options object
  823. * @param {boolean=} options.update whether a new variable should be created or the existing one updated
  824. * @param {Module} options.module the module
  825. * @param {Module} options.originModule module in which the statement is emitted
  826. * @param {ModuleGraph} options.moduleGraph the module graph
  827. * @param {ChunkGraph} options.chunkGraph the chunk graph
  828. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  829. * @param {string} options.importVar name of the import variable
  830. * @param {string=} options.request the request that should be printed as comment
  831. * @param {boolean=} options.weak true, if this is a weak dependency
  832. * @param {ModuleDependency=} options.dependency module dependency
  833. * @returns {[string, string]} the import statement and the compat statement
  834. */
  835. importStatement({
  836. update,
  837. module,
  838. moduleGraph,
  839. chunkGraph,
  840. request,
  841. importVar,
  842. originModule,
  843. weak,
  844. dependency,
  845. runtimeRequirements
  846. }) {
  847. if (!module) {
  848. return [
  849. this.missingModuleStatement({
  850. request
  851. }),
  852. ""
  853. ];
  854. }
  855. if (chunkGraph.getModuleId(module) === null) {
  856. if (weak) {
  857. // only weak referenced modules don't get an id
  858. // we can always emit an error emitting code here
  859. return [
  860. this.weakError({
  861. module,
  862. chunkGraph,
  863. request,
  864. type: "statements"
  865. }),
  866. ""
  867. ];
  868. }
  869. throw new Error(
  870. `RuntimeTemplate.importStatement(): ${noModuleIdErrorMessage(
  871. module,
  872. chunkGraph
  873. )}`
  874. );
  875. }
  876. const moduleId = this.moduleId({
  877. module,
  878. chunkGraph,
  879. request,
  880. weak
  881. });
  882. const optDeclaration = update ? "" : "var ";
  883. const exportsType = module.getExportsType(
  884. chunkGraph.moduleGraph,
  885. /** @type {BuildMeta} */
  886. (originModule.buildMeta).strictHarmonyModule
  887. );
  888. runtimeRequirements.add(RuntimeGlobals.require);
  889. /** @type {string} */
  890. let importContent;
  891. const isModuleDeferred =
  892. (dependency instanceof getHarmonyImportDependency() ||
  893. dependency instanceof getImportDependency()) &&
  894. ImportPhaseUtils.isDefer(dependency.phase) &&
  895. !(/** @type {BuildMeta} */ (module.buildMeta).async);
  896. if (isModuleDeferred) {
  897. /** @type {Set<Module>} */
  898. const outgoingAsyncModules = getOutgoingAsyncModules(moduleGraph, module);
  899. importContent = `/* deferred harmony import */ ${optDeclaration}${importVar} = ${getOptimizedDeferredModule(
  900. moduleId,
  901. exportsType,
  902. Array.from(outgoingAsyncModules, (mod) => chunkGraph.getModuleId(mod)),
  903. runtimeRequirements
  904. )};\n`;
  905. return [importContent, ""];
  906. }
  907. importContent = `/* harmony import */ ${optDeclaration}${importVar} = ${RuntimeGlobals.require}(${moduleId});\n`;
  908. if (exportsType === "dynamic") {
  909. runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport);
  910. return [
  911. importContent,
  912. `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${importVar});\n`
  913. ];
  914. }
  915. return [importContent, ""];
  916. }
  917. /**
  918. * Export from import.
  919. * @template GenerateContext
  920. * @param {object} options options
  921. * @param {ModuleGraph} options.moduleGraph the module graph
  922. * @param {ChunkGraph} options.chunkGraph the chunk graph
  923. * @param {Module} options.module the module
  924. * @param {string} options.request the request
  925. * @param {string | string[]} options.exportName the export name
  926. * @param {Module} options.originModule the origin module
  927. * @param {boolean | undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted
  928. * @param {boolean | undefined} options.isCall true, if expression will be called
  929. * @param {boolean | null} options.callContext when false, call context will not be preserved
  930. * @param {boolean} options.defaultInterop when true and accessing the default exports, interop code will be generated
  931. * @param {string} options.importVar the identifier name of the import variable
  932. * @param {InitFragment<GenerateContext>[]} options.initFragments init fragments will be added here
  933. * @param {RuntimeSpec} options.runtime runtime for which this code will be generated
  934. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  935. * @param {ModuleDependency} options.dependency module dependency
  936. * @returns {string} expression
  937. */
  938. exportFromImport({
  939. moduleGraph,
  940. chunkGraph,
  941. module,
  942. request,
  943. exportName,
  944. originModule,
  945. asiSafe,
  946. isCall,
  947. callContext,
  948. defaultInterop,
  949. importVar,
  950. initFragments,
  951. runtime,
  952. runtimeRequirements,
  953. dependency
  954. }) {
  955. if (!module) {
  956. return this.missingModule({
  957. request
  958. });
  959. }
  960. if (!Array.isArray(exportName)) {
  961. exportName = exportName ? [exportName] : [];
  962. }
  963. const exportsType = module.getExportsType(
  964. moduleGraph,
  965. /** @type {BuildMeta} */
  966. (originModule.buildMeta).strictHarmonyModule
  967. );
  968. const isModuleDeferred =
  969. (dependency instanceof getHarmonyImportDependency() ||
  970. dependency instanceof getImportDependency()) &&
  971. ImportPhaseUtils.isDefer(dependency.phase) &&
  972. !(/** @type {BuildMeta} */ (module.buildMeta).async);
  973. if (defaultInterop) {
  974. // when the defaultInterop is used (when a ESM imports a CJS module),
  975. if (exportName.length > 0 && exportName[0] === "default") {
  976. if (isModuleDeferred && exportsType !== "namespace") {
  977. const exportsInfo = moduleGraph.getExportsInfo(module);
  978. const name = exportName.slice(1);
  979. const used = exportsInfo.getUsedName(name, runtime);
  980. if (!used) {
  981. const comment = Template.toNormalComment(
  982. `unused export ${propertyAccess(exportName)}`
  983. );
  984. return `${comment} undefined`;
  985. }
  986. const access = `${importVar}.a${propertyAccess(used)}`;
  987. if (isCall || asiSafe === undefined) {
  988. return access;
  989. }
  990. return asiSafe ? `(${access})` : `;(${access})`;
  991. }
  992. // accessing the .default property is same thing as `require()` the module.
  993. // For example:
  994. // import mod from "cjs"; mod.default.x;
  995. // is translated to
  996. // var mod = require("cjs"); mod.x;
  997. switch (exportsType) {
  998. case "dynamic":
  999. if (isCall) {
  1000. return `${importVar}_default()${propertyAccess(exportName, 1)}`;
  1001. }
  1002. return asiSafe
  1003. ? `(${importVar}_default()${propertyAccess(exportName, 1)})`
  1004. : asiSafe === false
  1005. ? `;(${importVar}_default()${propertyAccess(exportName, 1)})`
  1006. : `${importVar}_default.a${propertyAccess(exportName, 1)}`;
  1007. case "default-only":
  1008. case "default-with-named":
  1009. exportName = exportName.slice(1);
  1010. break;
  1011. }
  1012. } else if (exportName.length > 0) {
  1013. // the property used is not .default.
  1014. // For example:
  1015. // import * as ns from "cjs"; cjs.prop;
  1016. if (exportsType === "default-only") {
  1017. // in the strictest case, it is a runtime error (e.g. NodeJS behavior of CJS-ESM interop).
  1018. return `/* non-default import from non-esm module */undefined${propertyAccess(
  1019. exportName,
  1020. 1
  1021. )}`;
  1022. } else if (
  1023. exportsType !== "namespace" &&
  1024. exportName[0] === "__esModule"
  1025. ) {
  1026. return "/* __esModule */true";
  1027. }
  1028. } else if (isModuleDeferred) {
  1029. // now exportName.length is 0
  1030. // fall through to the end of this function, create the namespace there.
  1031. } else if (
  1032. exportsType === "default-only" ||
  1033. exportsType === "default-with-named"
  1034. ) {
  1035. // now exportName.length is 0, which means the namespace object is used in an unknown way
  1036. // for example:
  1037. // import * as ns from "cjs"; console.log(ns);
  1038. // we will need to createFakeNamespaceObject that simulates ES Module namespace object
  1039. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  1040. initFragments.push(
  1041. new InitFragment(
  1042. `var ${importVar}_namespace_cache;\n`,
  1043. InitFragment.STAGE_CONSTANTS,
  1044. -1,
  1045. `${importVar}_namespace_cache`
  1046. )
  1047. );
  1048. return `/*#__PURE__*/ ${
  1049. asiSafe ? "" : asiSafe === false ? ";" : "Object"
  1050. }(${importVar}_namespace_cache || (${importVar}_namespace_cache = ${
  1051. RuntimeGlobals.createFakeNamespaceObject
  1052. }(${importVar}${exportsType === "default-only" ? "" : ", 2"})))`;
  1053. }
  1054. }
  1055. if (exportName.length > 0) {
  1056. const exportsInfo = moduleGraph.getExportsInfo(module);
  1057. // in some case the exported item is renamed (get this by getUsedName). for example,
  1058. // x.default might be emitted as x.Z (default is renamed to Z)
  1059. const used = exportsInfo.getUsedName(exportName, runtime);
  1060. if (!used) {
  1061. const comment = Template.toNormalComment(
  1062. `unused export ${propertyAccess(exportName)}`
  1063. );
  1064. return `${comment} undefined`;
  1065. }
  1066. const comment = equals(used, exportName)
  1067. ? ""
  1068. : `${Template.toNormalComment(propertyAccess(exportName))} `;
  1069. const access = `${importVar}${
  1070. isModuleDeferred ? ".a" : ""
  1071. }${comment}${propertyAccess(used)}`;
  1072. if (isCall && callContext === false) {
  1073. return asiSafe
  1074. ? `(0,${access})`
  1075. : asiSafe === false
  1076. ? `;(0,${access})`
  1077. : `/*#__PURE__*/Object(${access})`;
  1078. }
  1079. return access;
  1080. }
  1081. if (isModuleDeferred) {
  1082. initFragments.push(
  1083. new InitFragment(
  1084. `var ${importVar}_deferred_namespace_cache;\n`,
  1085. InitFragment.STAGE_CONSTANTS,
  1086. -1,
  1087. `${importVar}_deferred_namespace_cache`
  1088. )
  1089. );
  1090. runtimeRequirements.add(RuntimeGlobals.makeDeferredNamespaceObject);
  1091. const id = chunkGraph.getModuleId(module);
  1092. const type = getMakeDeferredNamespaceModeFromExportsType(exportsType);
  1093. const init = `${
  1094. RuntimeGlobals.makeDeferredNamespaceObject
  1095. }(${JSON.stringify(id)}, ${type})`;
  1096. return `/*#__PURE__*/ ${
  1097. asiSafe ? "" : asiSafe === false ? ";" : "Object"
  1098. }(${importVar}_deferred_namespace_cache || (${importVar}_deferred_namespace_cache = ${init}))`;
  1099. }
  1100. // if we hit here, the importVar is either
  1101. // - already a ES module namespace object
  1102. // - or imported by a way that does not need interop.
  1103. return importVar;
  1104. }
  1105. /**
  1106. * Returns expression.
  1107. * @param {object} options options
  1108. * @param {AsyncDependenciesBlock | undefined} options.block the async block
  1109. * @param {string} options.message the message
  1110. * @param {ChunkGraph} options.chunkGraph the chunk graph
  1111. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1112. * @returns {string} expression
  1113. */
  1114. blockPromise({ block, message, chunkGraph, runtimeRequirements }) {
  1115. if (!block) {
  1116. const comment = this.comment({
  1117. message
  1118. });
  1119. return `Promise.resolve(${comment.trim()})`;
  1120. }
  1121. const chunkGroup = chunkGraph.getBlockChunkGroup(block);
  1122. if (!chunkGroup || chunkGroup.chunks.length === 0) {
  1123. const comment = this.comment({
  1124. message
  1125. });
  1126. return `Promise.resolve(${comment.trim()})`;
  1127. }
  1128. const chunks = chunkGroup.chunks.filter(
  1129. (chunk) => !chunk.hasRuntime() && chunk.id !== null
  1130. );
  1131. const comment = this.comment({
  1132. message,
  1133. chunkName: block.chunkName
  1134. });
  1135. if (chunks.length === 1) {
  1136. const chunkId = JSON.stringify(chunks[0].id);
  1137. runtimeRequirements.add(RuntimeGlobals.ensureChunk);
  1138. const fetchPriority = chunkGroup.options.fetchPriority;
  1139. if (fetchPriority) {
  1140. runtimeRequirements.add(RuntimeGlobals.hasFetchPriority);
  1141. }
  1142. return `${RuntimeGlobals.ensureChunk}(${comment}${chunkId}${
  1143. fetchPriority ? `, ${JSON.stringify(fetchPriority)}` : ""
  1144. })`;
  1145. } else if (chunks.length > 0) {
  1146. runtimeRequirements.add(RuntimeGlobals.ensureChunk);
  1147. const fetchPriority = chunkGroup.options.fetchPriority;
  1148. if (fetchPriority) {
  1149. runtimeRequirements.add(RuntimeGlobals.hasFetchPriority);
  1150. }
  1151. /**
  1152. * Returns require chunk id code.
  1153. * @param {Chunk} chunk chunk
  1154. * @returns {string} require chunk id code
  1155. */
  1156. const requireChunkId = (chunk) =>
  1157. `${RuntimeGlobals.ensureChunk}(${JSON.stringify(chunk.id)}${
  1158. fetchPriority ? `, ${JSON.stringify(fetchPriority)}` : ""
  1159. })`;
  1160. return `Promise.all(${comment.trim()}[${chunks
  1161. .map(requireChunkId)
  1162. .join(", ")}])`;
  1163. }
  1164. return `Promise.resolve(${comment.trim()})`;
  1165. }
  1166. /**
  1167. * Async module factory.
  1168. * @param {object} options options
  1169. * @param {AsyncDependenciesBlock} options.block the async block
  1170. * @param {ChunkGraph} options.chunkGraph the chunk graph
  1171. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1172. * @param {string=} options.request request string used originally
  1173. * @returns {string} expression
  1174. */
  1175. asyncModuleFactory({ block, chunkGraph, runtimeRequirements, request }) {
  1176. const dep = block.dependencies[0];
  1177. const module = chunkGraph.moduleGraph.getModule(dep);
  1178. const ensureChunk = this.blockPromise({
  1179. block,
  1180. message: "",
  1181. chunkGraph,
  1182. runtimeRequirements
  1183. });
  1184. const factory = this.returningFunction(
  1185. this.moduleRaw({
  1186. module,
  1187. chunkGraph,
  1188. request,
  1189. runtimeRequirements
  1190. })
  1191. );
  1192. return this.returningFunction(
  1193. ensureChunk.startsWith("Promise.resolve(")
  1194. ? `${factory}`
  1195. : `${ensureChunk}.then(${this.returningFunction(factory)})`
  1196. );
  1197. }
  1198. /**
  1199. * Sync module factory.
  1200. * @param {object} options options
  1201. * @param {Dependency} options.dependency the dependency
  1202. * @param {ChunkGraph} options.chunkGraph the chunk graph
  1203. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1204. * @param {string=} options.request request string used originally
  1205. * @returns {string} expression
  1206. */
  1207. syncModuleFactory({ dependency, chunkGraph, runtimeRequirements, request }) {
  1208. const module = chunkGraph.moduleGraph.getModule(dependency);
  1209. const factory = this.returningFunction(
  1210. this.moduleRaw({
  1211. module,
  1212. chunkGraph,
  1213. request,
  1214. runtimeRequirements
  1215. })
  1216. );
  1217. return this.returningFunction(factory);
  1218. }
  1219. /**
  1220. * Define es module flag statement.
  1221. * @param {object} options options
  1222. * @param {string} options.exportsArgument the name of the exports object
  1223. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1224. * @returns {string} statement
  1225. */
  1226. defineEsModuleFlagStatement({ exportsArgument, runtimeRequirements }) {
  1227. runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject);
  1228. runtimeRequirements.add(RuntimeGlobals.exports);
  1229. return `${RuntimeGlobals.makeNamespaceObject}(${exportsArgument});\n`;
  1230. }
  1231. }
  1232. module.exports = RuntimeTemplate;