RuntimeTemplate.js 39 KB

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