RuntimeTemplate.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  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. let content;
  316. if (this.outputOptions.pathinfo) {
  317. content = [message, request, chunkName, chunkReason]
  318. .filter(Boolean)
  319. .map((item) => this.requestShortener.shorten(item))
  320. .join(" | ");
  321. } else {
  322. content = [message, chunkName, chunkReason]
  323. .filter(Boolean)
  324. .map((item) => this.requestShortener.shorten(item))
  325. .join(" | ");
  326. }
  327. if (!content) return "";
  328. if (this.outputOptions.pathinfo) {
  329. return `${Template.toComment(content)} `;
  330. }
  331. return `${Template.toNormalComment(content)} `;
  332. }
  333. /**
  334. * @param {object} options generation options
  335. * @param {string=} options.request request string used originally
  336. * @returns {string} generated error block
  337. */
  338. throwMissingModuleErrorBlock({ request }) {
  339. const err = `Cannot find module '${request}'`;
  340. return `var e = new Error(${JSON.stringify(
  341. err
  342. )}); e.code = 'MODULE_NOT_FOUND'; throw e;`;
  343. }
  344. /**
  345. * @param {object} options generation options
  346. * @param {string=} options.request request string used originally
  347. * @returns {string} generated error function
  348. */
  349. throwMissingModuleErrorFunction({ request }) {
  350. return `function webpackMissingModule() { ${this.throwMissingModuleErrorBlock(
  351. { request }
  352. )} }`;
  353. }
  354. /**
  355. * @param {object} options generation options
  356. * @param {string=} options.request request string used originally
  357. * @returns {string} generated error IIFE
  358. */
  359. missingModule({ request }) {
  360. return `Object(${this.throwMissingModuleErrorFunction({ request })}())`;
  361. }
  362. /**
  363. * @param {object} options generation options
  364. * @param {string=} options.request request string used originally
  365. * @returns {string} generated error statement
  366. */
  367. missingModuleStatement({ request }) {
  368. return `${this.missingModule({ request })};\n`;
  369. }
  370. /**
  371. * @param {object} options generation options
  372. * @param {string=} options.request request string used originally
  373. * @returns {string} generated error code
  374. */
  375. missingModulePromise({ request }) {
  376. return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({
  377. request
  378. })})`;
  379. }
  380. /**
  381. * @param {object} options options object
  382. * @param {ChunkGraph} options.chunkGraph the chunk graph
  383. * @param {Module} options.module the module
  384. * @param {string=} options.request the request that should be printed as comment
  385. * @param {string=} options.idExpr expression to use as id expression
  386. * @param {"expression" | "promise" | "statements"} options.type which kind of code should be returned
  387. * @returns {string} the code
  388. */
  389. weakError({ module, chunkGraph, request, idExpr, type }) {
  390. const moduleId = chunkGraph.getModuleId(module);
  391. const errorMessage =
  392. moduleId === null
  393. ? JSON.stringify("Module is not available (weak dependency)")
  394. : idExpr
  395. ? `"Module '" + ${idExpr} + "' is not available (weak dependency)"`
  396. : JSON.stringify(
  397. `Module '${moduleId}' is not available (weak dependency)`
  398. );
  399. const comment = request ? `${Template.toNormalComment(request)} ` : "";
  400. const errorStatements = `var e = new Error(${errorMessage}); ${
  401. comment
  402. }e.code = 'MODULE_NOT_FOUND'; throw e;`;
  403. switch (type) {
  404. case "statements":
  405. return errorStatements;
  406. case "promise":
  407. return `Promise.resolve().then(${this.basicFunction(
  408. "",
  409. errorStatements
  410. )})`;
  411. case "expression":
  412. return this.iife("", errorStatements);
  413. }
  414. }
  415. /**
  416. * @param {object} options options object
  417. * @param {Module} options.module the module
  418. * @param {ChunkGraph} options.chunkGraph the chunk graph
  419. * @param {string=} options.request the request that should be printed as comment
  420. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  421. * @returns {string} the expression
  422. */
  423. moduleId({ module, chunkGraph, request, weak }) {
  424. if (!module) {
  425. return this.missingModule({
  426. request
  427. });
  428. }
  429. const moduleId = chunkGraph.getModuleId(module);
  430. if (moduleId === null) {
  431. if (weak) {
  432. return "null /* weak dependency, without id */";
  433. }
  434. throw new Error(
  435. `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage(
  436. module,
  437. chunkGraph
  438. )}`
  439. );
  440. }
  441. return `${this.comment({ request })}${JSON.stringify(moduleId)}`;
  442. }
  443. /**
  444. * @param {object} options options object
  445. * @param {Module | null} options.module the module
  446. * @param {ChunkGraph} options.chunkGraph the chunk graph
  447. * @param {string=} options.request the request that should be printed as comment
  448. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  449. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  450. * @returns {string} the expression
  451. */
  452. moduleRaw({ module, chunkGraph, request, weak, runtimeRequirements }) {
  453. if (!module) {
  454. return this.missingModule({
  455. request
  456. });
  457. }
  458. const moduleId = chunkGraph.getModuleId(module);
  459. if (moduleId === null) {
  460. if (weak) {
  461. // only weak referenced modules don't get an id
  462. // we can always emit an error emitting code here
  463. return this.weakError({
  464. module,
  465. chunkGraph,
  466. request,
  467. type: "expression"
  468. });
  469. }
  470. throw new Error(
  471. `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage(
  472. module,
  473. chunkGraph
  474. )}`
  475. );
  476. }
  477. runtimeRequirements.add(RuntimeGlobals.require);
  478. return `${RuntimeGlobals.require}(${this.moduleId({
  479. module,
  480. chunkGraph,
  481. request,
  482. weak
  483. })})`;
  484. }
  485. /**
  486. * @param {object} options options object
  487. * @param {Module | null} options.module the module
  488. * @param {ChunkGraph} options.chunkGraph the chunk graph
  489. * @param {string} options.request the request that should be printed as comment
  490. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  491. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  492. * @returns {string} the expression
  493. */
  494. moduleExports({ module, chunkGraph, request, weak, runtimeRequirements }) {
  495. return this.moduleRaw({
  496. module,
  497. chunkGraph,
  498. request,
  499. weak,
  500. runtimeRequirements
  501. });
  502. }
  503. /**
  504. * @param {object} options options object
  505. * @param {Module} options.module the module
  506. * @param {ChunkGraph} options.chunkGraph the chunk graph
  507. * @param {string} options.request the request that should be printed as comment
  508. * @param {boolean=} options.strict if the current module is in strict esm mode
  509. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  510. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  511. * @returns {string} the expression
  512. */
  513. moduleNamespace({
  514. module,
  515. chunkGraph,
  516. request,
  517. strict,
  518. weak,
  519. runtimeRequirements
  520. }) {
  521. if (!module) {
  522. return this.missingModule({
  523. request
  524. });
  525. }
  526. if (chunkGraph.getModuleId(module) === null) {
  527. if (weak) {
  528. // only weak referenced modules don't get an id
  529. // we can always emit an error emitting code here
  530. return this.weakError({
  531. module,
  532. chunkGraph,
  533. request,
  534. type: "expression"
  535. });
  536. }
  537. throw new Error(
  538. `RuntimeTemplate.moduleNamespace(): ${noModuleIdErrorMessage(
  539. module,
  540. chunkGraph
  541. )}`
  542. );
  543. }
  544. const moduleId = this.moduleId({
  545. module,
  546. chunkGraph,
  547. request,
  548. weak
  549. });
  550. const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict);
  551. switch (exportsType) {
  552. case "namespace":
  553. return this.moduleRaw({
  554. module,
  555. chunkGraph,
  556. request,
  557. weak,
  558. runtimeRequirements
  559. });
  560. case "default-with-named":
  561. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  562. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 3)`;
  563. case "default-only":
  564. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  565. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 1)`;
  566. case "dynamic":
  567. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  568. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 7)`;
  569. }
  570. }
  571. /**
  572. * @param {object} options options object
  573. * @param {ChunkGraph} options.chunkGraph the chunk graph
  574. * @param {AsyncDependenciesBlock=} options.block the current dependencies block
  575. * @param {Module} options.module the module
  576. * @param {string} options.request the request that should be printed as comment
  577. * @param {string} options.message a message for the comment
  578. * @param {boolean=} options.strict if the current module is in strict esm mode
  579. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  580. * @param {Dependency} options.dependency dependency
  581. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  582. * @returns {string} the promise expression
  583. */
  584. moduleNamespacePromise({
  585. chunkGraph,
  586. block,
  587. module,
  588. request,
  589. message,
  590. strict,
  591. weak,
  592. dependency,
  593. runtimeRequirements
  594. }) {
  595. if (!module) {
  596. return this.missingModulePromise({
  597. request
  598. });
  599. }
  600. const moduleId = chunkGraph.getModuleId(module);
  601. if (moduleId === null) {
  602. if (weak) {
  603. // only weak referenced modules don't get an id
  604. // we can always emit an error emitting code here
  605. return this.weakError({
  606. module,
  607. chunkGraph,
  608. request,
  609. type: "promise"
  610. });
  611. }
  612. throw new Error(
  613. `RuntimeTemplate.moduleNamespacePromise(): ${noModuleIdErrorMessage(
  614. module,
  615. chunkGraph
  616. )}`
  617. );
  618. }
  619. const promise = this.blockPromise({
  620. chunkGraph,
  621. block,
  622. message,
  623. runtimeRequirements
  624. });
  625. let appending;
  626. let idExpr = JSON.stringify(chunkGraph.getModuleId(module));
  627. const comment = this.comment({
  628. request
  629. });
  630. let header = "";
  631. if (weak) {
  632. if (idExpr.length > 8) {
  633. // 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"'
  634. header += `var id = ${idExpr}; `;
  635. idExpr = "id";
  636. }
  637. runtimeRequirements.add(RuntimeGlobals.moduleFactories);
  638. header += `if(!${
  639. RuntimeGlobals.moduleFactories
  640. }[${idExpr}]) { ${this.weakError({
  641. module,
  642. chunkGraph,
  643. request,
  644. idExpr,
  645. type: "statements"
  646. })} } `;
  647. }
  648. const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict);
  649. const isModuleDeferred =
  650. (dependency instanceof getHarmonyImportDependency() ||
  651. dependency instanceof getImportDependency()) &&
  652. ImportPhaseUtils.isDefer(dependency.phase) &&
  653. !(/** @type {BuildMeta} */ (module.buildMeta).async);
  654. if (isModuleDeferred) {
  655. runtimeRequirements.add(RuntimeGlobals.makeDeferredNamespaceObject);
  656. const mode = getMakeDeferredNamespaceModeFromExportsType(exportsType);
  657. const asyncDeps = Array.from(
  658. getOutgoingAsyncModules(chunkGraph.moduleGraph, module),
  659. (m) => chunkGraph.getModuleId(m)
  660. ).filter((id) => id !== null);
  661. if (asyncDeps.length) {
  662. if (header) {
  663. appending = `.then(${this.basicFunction(
  664. "",
  665. `${header}return ${RuntimeGlobals.deferredModuleAsyncTransitiveDependencies}(${JSON.stringify(asyncDeps)});`
  666. )})`;
  667. } else {
  668. runtimeRequirements.add(RuntimeGlobals.require);
  669. appending = `.then(${this.returningFunction(`${RuntimeGlobals.deferredModuleAsyncTransitiveDependencies}(${JSON.stringify(asyncDeps)})`)})`;
  670. }
  671. appending += `.then(${RuntimeGlobals.makeDeferredNamespaceObject}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}, ${mode}))`;
  672. } else if (header) {
  673. appending = `.then(${this.basicFunction(
  674. "",
  675. `${header}return ${RuntimeGlobals.makeDeferredNamespaceObject}(${comment}${idExpr}, ${mode});`
  676. )})`;
  677. } else {
  678. runtimeRequirements.add(RuntimeGlobals.require);
  679. appending = `.then(${RuntimeGlobals.makeDeferredNamespaceObject}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}, ${mode}))`;
  680. }
  681. } else {
  682. let fakeType = 16;
  683. switch (exportsType) {
  684. case "namespace":
  685. if (header) {
  686. const rawModule = this.moduleRaw({
  687. module,
  688. chunkGraph,
  689. request,
  690. weak,
  691. runtimeRequirements
  692. });
  693. appending = `.then(${this.basicFunction(
  694. "",
  695. `${header}return ${rawModule};`
  696. )})`;
  697. } else {
  698. runtimeRequirements.add(RuntimeGlobals.require);
  699. appending = `.then(${RuntimeGlobals.require}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}))`;
  700. }
  701. break;
  702. case "dynamic":
  703. fakeType |= 4;
  704. /* fall through */
  705. case "default-with-named":
  706. fakeType |= 2;
  707. /* fall through */
  708. case "default-only":
  709. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  710. if (chunkGraph.moduleGraph.isAsync(module)) {
  711. if (header) {
  712. const rawModule = this.moduleRaw({
  713. module,
  714. chunkGraph,
  715. request,
  716. weak,
  717. runtimeRequirements
  718. });
  719. appending = `.then(${this.basicFunction(
  720. "",
  721. `${header}return ${rawModule};`
  722. )})`;
  723. } else {
  724. runtimeRequirements.add(RuntimeGlobals.require);
  725. appending = `.then(${RuntimeGlobals.require}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}))`;
  726. }
  727. appending += `.then(${this.returningFunction(
  728. `${RuntimeGlobals.createFakeNamespaceObject}(m, ${fakeType})`,
  729. "m"
  730. )})`;
  731. } else {
  732. fakeType |= 1;
  733. if (header) {
  734. const moduleIdExpr = this.moduleId({
  735. module,
  736. chunkGraph,
  737. request,
  738. weak
  739. });
  740. const returnExpression = `${RuntimeGlobals.createFakeNamespaceObject}(${moduleIdExpr}, ${fakeType})`;
  741. appending = `.then(${this.basicFunction(
  742. "",
  743. `${header}return ${returnExpression};`
  744. )})`;
  745. } else {
  746. appending = `.then(${RuntimeGlobals.createFakeNamespaceObject}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}, ${fakeType}))`;
  747. }
  748. }
  749. break;
  750. }
  751. }
  752. return `${promise || "Promise.resolve()"}${appending}`;
  753. }
  754. /**
  755. * @param {object} options options object
  756. * @param {ChunkGraph} options.chunkGraph the chunk graph
  757. * @param {RuntimeSpec=} options.runtime runtime for which this code will be generated
  758. * @param {RuntimeSpec | boolean=} options.runtimeCondition only execute the statement in some runtimes
  759. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  760. * @returns {string} expression
  761. */
  762. runtimeConditionExpression({
  763. chunkGraph,
  764. runtimeCondition,
  765. runtime,
  766. runtimeRequirements
  767. }) {
  768. if (runtimeCondition === undefined) return "true";
  769. if (typeof runtimeCondition === "boolean") return `${runtimeCondition}`;
  770. /** @type {Set<string>} */
  771. const positiveRuntimeIds = new Set();
  772. forEachRuntime(runtimeCondition, (runtime) =>
  773. positiveRuntimeIds.add(
  774. `${chunkGraph.getRuntimeId(/** @type {string} */ (runtime))}`
  775. )
  776. );
  777. /** @type {Set<string>} */
  778. const negativeRuntimeIds = new Set();
  779. forEachRuntime(subtractRuntime(runtime, runtimeCondition), (runtime) =>
  780. negativeRuntimeIds.add(
  781. `${chunkGraph.getRuntimeId(/** @type {string} */ (runtime))}`
  782. )
  783. );
  784. runtimeRequirements.add(RuntimeGlobals.runtimeId);
  785. return compileBooleanMatcher.fromLists(
  786. [...positiveRuntimeIds],
  787. [...negativeRuntimeIds]
  788. )(RuntimeGlobals.runtimeId);
  789. }
  790. /**
  791. * @param {object} options options object
  792. * @param {boolean=} options.update whether a new variable should be created or the existing one updated
  793. * @param {Module} options.module the module
  794. * @param {ModuleGraph} options.moduleGraph the module graph
  795. * @param {ChunkGraph} options.chunkGraph the chunk graph
  796. * @param {string} options.request the request that should be printed as comment
  797. * @param {string} options.importVar name of the import variable
  798. * @param {Module} options.originModule module in which the statement is emitted
  799. * @param {boolean=} options.weak true, if this is a weak dependency
  800. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  801. * @param {ModuleDependency} options.dependency module dependency
  802. * @returns {[string, string]} the import statement and the compat statement
  803. */
  804. importStatement({
  805. update,
  806. module,
  807. moduleGraph,
  808. chunkGraph,
  809. request,
  810. importVar,
  811. originModule,
  812. weak,
  813. dependency,
  814. runtimeRequirements
  815. }) {
  816. if (!module) {
  817. return [
  818. this.missingModuleStatement({
  819. request
  820. }),
  821. ""
  822. ];
  823. }
  824. if (chunkGraph.getModuleId(module) === null) {
  825. if (weak) {
  826. // only weak referenced modules don't get an id
  827. // we can always emit an error emitting code here
  828. return [
  829. this.weakError({
  830. module,
  831. chunkGraph,
  832. request,
  833. type: "statements"
  834. }),
  835. ""
  836. ];
  837. }
  838. throw new Error(
  839. `RuntimeTemplate.importStatement(): ${noModuleIdErrorMessage(
  840. module,
  841. chunkGraph
  842. )}`
  843. );
  844. }
  845. const moduleId = this.moduleId({
  846. module,
  847. chunkGraph,
  848. request,
  849. weak
  850. });
  851. const optDeclaration = update ? "" : "var ";
  852. const exportsType = module.getExportsType(
  853. chunkGraph.moduleGraph,
  854. /** @type {BuildMeta} */
  855. (originModule.buildMeta).strictHarmonyModule
  856. );
  857. runtimeRequirements.add(RuntimeGlobals.require);
  858. let importContent;
  859. const isModuleDeferred =
  860. (dependency instanceof getHarmonyImportDependency() ||
  861. dependency instanceof getImportDependency()) &&
  862. ImportPhaseUtils.isDefer(dependency.phase) &&
  863. !(/** @type {BuildMeta} */ (module.buildMeta).async);
  864. if (isModuleDeferred) {
  865. /** @type {Set<Module>} */
  866. const outgoingAsyncModules = getOutgoingAsyncModules(moduleGraph, module);
  867. importContent = `/* deferred harmony import */ ${optDeclaration}${importVar} = ${getOptimizedDeferredModule(
  868. moduleId,
  869. exportsType,
  870. Array.from(outgoingAsyncModules, (mod) => chunkGraph.getModuleId(mod)),
  871. runtimeRequirements
  872. )};\n`;
  873. return [importContent, ""];
  874. }
  875. importContent = `/* harmony import */ ${optDeclaration}${importVar} = ${RuntimeGlobals.require}(${moduleId});\n`;
  876. if (exportsType === "dynamic") {
  877. runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport);
  878. return [
  879. importContent,
  880. `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${importVar});\n`
  881. ];
  882. }
  883. return [importContent, ""];
  884. }
  885. /**
  886. * @template GenerateContext
  887. * @param {object} options options
  888. * @param {ModuleGraph} options.moduleGraph the module graph
  889. * @param {ChunkGraph} options.chunkGraph the chunk graph
  890. * @param {Module} options.module the module
  891. * @param {string} options.request the request
  892. * @param {string | string[]} options.exportName the export name
  893. * @param {Module} options.originModule the origin module
  894. * @param {boolean | undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted
  895. * @param {boolean} options.isCall true, if expression will be called
  896. * @param {boolean | null} options.callContext when false, call context will not be preserved
  897. * @param {boolean} options.defaultInterop when true and accessing the default exports, interop code will be generated
  898. * @param {string} options.importVar the identifier name of the import variable
  899. * @param {InitFragment<GenerateContext>[]} options.initFragments init fragments will be added here
  900. * @param {RuntimeSpec} options.runtime runtime for which this code will be generated
  901. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  902. * @param {ModuleDependency} options.dependency module dependency
  903. * @returns {string} expression
  904. */
  905. exportFromImport({
  906. moduleGraph,
  907. chunkGraph,
  908. module,
  909. request,
  910. exportName,
  911. originModule,
  912. asiSafe,
  913. isCall,
  914. callContext,
  915. defaultInterop,
  916. importVar,
  917. initFragments,
  918. runtime,
  919. runtimeRequirements,
  920. dependency
  921. }) {
  922. if (!module) {
  923. return this.missingModule({
  924. request
  925. });
  926. }
  927. if (!Array.isArray(exportName)) {
  928. exportName = exportName ? [exportName] : [];
  929. }
  930. const exportsType = module.getExportsType(
  931. moduleGraph,
  932. /** @type {BuildMeta} */
  933. (originModule.buildMeta).strictHarmonyModule
  934. );
  935. const isModuleDeferred =
  936. (dependency instanceof getHarmonyImportDependency() ||
  937. dependency instanceof getImportDependency()) &&
  938. ImportPhaseUtils.isDefer(dependency.phase) &&
  939. !(/** @type {BuildMeta} */ (module.buildMeta).async);
  940. if (defaultInterop) {
  941. // when the defaultInterop is used (when a ESM imports a CJS module),
  942. if (exportName.length > 0 && exportName[0] === "default") {
  943. if (isModuleDeferred && exportsType !== "namespace") {
  944. const exportsInfo = moduleGraph.getExportsInfo(module);
  945. const name = exportName.slice(1);
  946. const used = exportsInfo.getUsedName(name, runtime);
  947. if (!used) {
  948. const comment = Template.toNormalComment(
  949. `unused export ${propertyAccess(exportName)}`
  950. );
  951. return `${comment} undefined`;
  952. }
  953. const access = `${importVar}.a${propertyAccess(used)}`;
  954. if (isCall || asiSafe === undefined) {
  955. return access;
  956. }
  957. return asiSafe ? `(${access})` : `;(${access})`;
  958. }
  959. // accessing the .default property is same thing as `require()` the module.
  960. // For example:
  961. // import mod from "cjs"; mod.default.x;
  962. // is translated to
  963. // var mod = require("cjs"); mod.x;
  964. switch (exportsType) {
  965. case "dynamic":
  966. if (isCall) {
  967. return `${importVar}_default()${propertyAccess(exportName, 1)}`;
  968. }
  969. return asiSafe
  970. ? `(${importVar}_default()${propertyAccess(exportName, 1)})`
  971. : asiSafe === false
  972. ? `;(${importVar}_default()${propertyAccess(exportName, 1)})`
  973. : `${importVar}_default.a${propertyAccess(exportName, 1)}`;
  974. case "default-only":
  975. case "default-with-named":
  976. exportName = exportName.slice(1);
  977. break;
  978. }
  979. } else if (exportName.length > 0) {
  980. // the property used is not .default.
  981. // For example:
  982. // import * as ns from "cjs"; cjs.prop;
  983. if (exportsType === "default-only") {
  984. // in the strictest case, it is a runtime error (e.g. NodeJS behavior of CJS-ESM interop).
  985. return `/* non-default import from non-esm module */undefined${propertyAccess(
  986. exportName,
  987. 1
  988. )}`;
  989. } else if (
  990. exportsType !== "namespace" &&
  991. exportName[0] === "__esModule"
  992. ) {
  993. return "/* __esModule */true";
  994. }
  995. } else if (isModuleDeferred) {
  996. // now exportName.length is 0
  997. // fall through to the end of this function, create the namespace there.
  998. } else if (
  999. exportsType === "default-only" ||
  1000. exportsType === "default-with-named"
  1001. ) {
  1002. // now exportName.length is 0, which means the namespace object is used in an unknown way
  1003. // for example:
  1004. // import * as ns from "cjs"; console.log(ns);
  1005. // we will need to createFakeNamespaceObject that simulates ES Module namespace object
  1006. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  1007. initFragments.push(
  1008. new InitFragment(
  1009. `var ${importVar}_namespace_cache;\n`,
  1010. InitFragment.STAGE_CONSTANTS,
  1011. -1,
  1012. `${importVar}_namespace_cache`
  1013. )
  1014. );
  1015. return `/*#__PURE__*/ ${
  1016. asiSafe ? "" : asiSafe === false ? ";" : "Object"
  1017. }(${importVar}_namespace_cache || (${importVar}_namespace_cache = ${
  1018. RuntimeGlobals.createFakeNamespaceObject
  1019. }(${importVar}${exportsType === "default-only" ? "" : ", 2"})))`;
  1020. }
  1021. }
  1022. if (exportName.length > 0) {
  1023. const exportsInfo = moduleGraph.getExportsInfo(module);
  1024. // in some case the exported item is renamed (get this by getUsedName). for example,
  1025. // x.default might be emitted as x.Z (default is renamed to Z)
  1026. const used = exportsInfo.getUsedName(exportName, runtime);
  1027. if (!used) {
  1028. const comment = Template.toNormalComment(
  1029. `unused export ${propertyAccess(exportName)}`
  1030. );
  1031. return `${comment} undefined`;
  1032. }
  1033. const comment = equals(used, exportName)
  1034. ? ""
  1035. : `${Template.toNormalComment(propertyAccess(exportName))} `;
  1036. const access = `${importVar}${
  1037. isModuleDeferred ? ".a" : ""
  1038. }${comment}${propertyAccess(used)}`;
  1039. if (isCall && callContext === false) {
  1040. return asiSafe
  1041. ? `(0,${access})`
  1042. : asiSafe === false
  1043. ? `;(0,${access})`
  1044. : `/*#__PURE__*/Object(${access})`;
  1045. }
  1046. return access;
  1047. }
  1048. if (isModuleDeferred) {
  1049. initFragments.push(
  1050. new InitFragment(
  1051. `var ${importVar}_deferred_namespace_cache;\n`,
  1052. InitFragment.STAGE_CONSTANTS,
  1053. -1,
  1054. `${importVar}_deferred_namespace_cache`
  1055. )
  1056. );
  1057. runtimeRequirements.add(RuntimeGlobals.makeDeferredNamespaceObject);
  1058. const id = chunkGraph.getModuleId(module);
  1059. const type = getMakeDeferredNamespaceModeFromExportsType(exportsType);
  1060. const init = `${
  1061. RuntimeGlobals.makeDeferredNamespaceObject
  1062. }(${JSON.stringify(id)}, ${type})`;
  1063. return `/*#__PURE__*/ ${
  1064. asiSafe ? "" : asiSafe === false ? ";" : "Object"
  1065. }(${importVar}_deferred_namespace_cache || (${importVar}_deferred_namespace_cache = ${init}))`;
  1066. }
  1067. // if we hit here, the importVar is either
  1068. // - already a ES module namespace object
  1069. // - or imported by a way that does not need interop.
  1070. return importVar;
  1071. }
  1072. /**
  1073. * @param {object} options options
  1074. * @param {AsyncDependenciesBlock | undefined} options.block the async block
  1075. * @param {string} options.message the message
  1076. * @param {ChunkGraph} options.chunkGraph the chunk graph
  1077. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1078. * @returns {string} expression
  1079. */
  1080. blockPromise({ block, message, chunkGraph, runtimeRequirements }) {
  1081. if (!block) {
  1082. const comment = this.comment({
  1083. message
  1084. });
  1085. return `Promise.resolve(${comment.trim()})`;
  1086. }
  1087. const chunkGroup = chunkGraph.getBlockChunkGroup(block);
  1088. if (!chunkGroup || chunkGroup.chunks.length === 0) {
  1089. const comment = this.comment({
  1090. message
  1091. });
  1092. return `Promise.resolve(${comment.trim()})`;
  1093. }
  1094. const chunks = chunkGroup.chunks.filter(
  1095. (chunk) => !chunk.hasRuntime() && chunk.id !== null
  1096. );
  1097. const comment = this.comment({
  1098. message,
  1099. chunkName: block.chunkName
  1100. });
  1101. if (chunks.length === 1) {
  1102. const chunkId = JSON.stringify(chunks[0].id);
  1103. runtimeRequirements.add(RuntimeGlobals.ensureChunk);
  1104. const fetchPriority = chunkGroup.options.fetchPriority;
  1105. if (fetchPriority) {
  1106. runtimeRequirements.add(RuntimeGlobals.hasFetchPriority);
  1107. }
  1108. return `${RuntimeGlobals.ensureChunk}(${comment}${chunkId}${
  1109. fetchPriority ? `, ${JSON.stringify(fetchPriority)}` : ""
  1110. })`;
  1111. } else if (chunks.length > 0) {
  1112. runtimeRequirements.add(RuntimeGlobals.ensureChunk);
  1113. const fetchPriority = chunkGroup.options.fetchPriority;
  1114. if (fetchPriority) {
  1115. runtimeRequirements.add(RuntimeGlobals.hasFetchPriority);
  1116. }
  1117. /**
  1118. * @param {Chunk} chunk chunk
  1119. * @returns {string} require chunk id code
  1120. */
  1121. const requireChunkId = (chunk) =>
  1122. `${RuntimeGlobals.ensureChunk}(${JSON.stringify(chunk.id)}${
  1123. fetchPriority ? `, ${JSON.stringify(fetchPriority)}` : ""
  1124. })`;
  1125. return `Promise.all(${comment.trim()}[${chunks
  1126. .map(requireChunkId)
  1127. .join(", ")}])`;
  1128. }
  1129. return `Promise.resolve(${comment.trim()})`;
  1130. }
  1131. /**
  1132. * @param {object} options options
  1133. * @param {AsyncDependenciesBlock} options.block the async block
  1134. * @param {ChunkGraph} options.chunkGraph the chunk graph
  1135. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1136. * @param {string=} options.request request string used originally
  1137. * @returns {string} expression
  1138. */
  1139. asyncModuleFactory({ block, chunkGraph, runtimeRequirements, request }) {
  1140. const dep = block.dependencies[0];
  1141. const module = chunkGraph.moduleGraph.getModule(dep);
  1142. const ensureChunk = this.blockPromise({
  1143. block,
  1144. message: "",
  1145. chunkGraph,
  1146. runtimeRequirements
  1147. });
  1148. const factory = this.returningFunction(
  1149. this.moduleRaw({
  1150. module,
  1151. chunkGraph,
  1152. request,
  1153. runtimeRequirements
  1154. })
  1155. );
  1156. return this.returningFunction(
  1157. ensureChunk.startsWith("Promise.resolve(")
  1158. ? `${factory}`
  1159. : `${ensureChunk}.then(${this.returningFunction(factory)})`
  1160. );
  1161. }
  1162. /**
  1163. * @param {object} options options
  1164. * @param {Dependency} options.dependency the dependency
  1165. * @param {ChunkGraph} options.chunkGraph the chunk graph
  1166. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1167. * @param {string=} options.request request string used originally
  1168. * @returns {string} expression
  1169. */
  1170. syncModuleFactory({ dependency, chunkGraph, runtimeRequirements, request }) {
  1171. const module = chunkGraph.moduleGraph.getModule(dependency);
  1172. const factory = this.returningFunction(
  1173. this.moduleRaw({
  1174. module,
  1175. chunkGraph,
  1176. request,
  1177. runtimeRequirements
  1178. })
  1179. );
  1180. return this.returningFunction(factory);
  1181. }
  1182. /**
  1183. * @param {object} options options
  1184. * @param {string} options.exportsArgument the name of the exports object
  1185. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1186. * @returns {string} statement
  1187. */
  1188. defineEsModuleFlagStatement({ exportsArgument, runtimeRequirements }) {
  1189. runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject);
  1190. runtimeRequirements.add(RuntimeGlobals.exports);
  1191. return `${RuntimeGlobals.makeNamespaceObject}(${exportsArgument});\n`;
  1192. }
  1193. }
  1194. module.exports = RuntimeTemplate;