RuntimeTemplate.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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 { equals } = require("./util/ArrayHelpers");
  10. const compileBooleanMatcher = require("./util/compileBooleanMatcher");
  11. const propertyAccess = require("./util/propertyAccess");
  12. const { forEachRuntime, subtractRuntime } = require("./util/runtime");
  13. /** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */
  14. /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
  15. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  16. /** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
  17. /** @typedef {import("./Compilation")} Compilation */
  18. /** @typedef {import("./Dependency")} Dependency */
  19. /** @typedef {import("./Module")} Module */
  20. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  21. /** @typedef {import("./RequestShortener")} RequestShortener */
  22. /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
  23. /**
  24. * @param {Module} module the module
  25. * @param {ChunkGraph} chunkGraph the chunk graph
  26. * @returns {string} error message
  27. */
  28. const noModuleIdErrorMessage = (module, chunkGraph) => {
  29. return `Module ${module.identifier()} has no id assigned.
  30. This should not happen.
  31. It's in these chunks: ${
  32. Array.from(
  33. chunkGraph.getModuleChunksIterable(module),
  34. c => c.name || c.id || c.debugId
  35. ).join(", ") || "none"
  36. } (If module is in no chunk this indicates a bug in some chunk/module optimization logic)
  37. Module has these incoming connections: ${Array.from(
  38. chunkGraph.moduleGraph.getIncomingConnections(module),
  39. connection =>
  40. `\n - ${
  41. connection.originModule && connection.originModule.identifier()
  42. } ${connection.dependency && connection.dependency.type} ${
  43. (connection.explanations &&
  44. Array.from(connection.explanations).join(", ")) ||
  45. ""
  46. }`
  47. ).join("")}`;
  48. };
  49. /**
  50. * @param {string|undefined} definition global object definition
  51. * @returns {string} save to use global object
  52. */
  53. function getGlobalObject(definition) {
  54. if (!definition) return definition;
  55. const trimmed = definition.trim();
  56. if (
  57. // identifier, we do not need real identifier regarding ECMAScript/Unicode
  58. trimmed.match(/^[_\p{L}][_0-9\p{L}]*$/iu) ||
  59. // iife
  60. // call expression
  61. // expression in parentheses
  62. trimmed.match(/^([_\p{L}][_0-9\p{L}]*)?\(.*\)$/iu)
  63. )
  64. return trimmed;
  65. return `Object(${trimmed})`;
  66. }
  67. class RuntimeTemplate {
  68. /**
  69. * @param {Compilation} compilation the compilation
  70. * @param {OutputOptions} outputOptions the compilation output options
  71. * @param {RequestShortener} requestShortener the request shortener
  72. */
  73. constructor(compilation, outputOptions, requestShortener) {
  74. this.compilation = compilation;
  75. this.outputOptions = outputOptions || {};
  76. this.requestShortener = requestShortener;
  77. this.globalObject = getGlobalObject(outputOptions.globalObject);
  78. this.contentHashReplacement = "X".repeat(outputOptions.hashDigestLength);
  79. }
  80. isIIFE() {
  81. return this.outputOptions.iife;
  82. }
  83. isModule() {
  84. return this.outputOptions.module;
  85. }
  86. supportsConst() {
  87. return this.outputOptions.environment.const;
  88. }
  89. supportsArrowFunction() {
  90. return this.outputOptions.environment.arrowFunction;
  91. }
  92. supportsOptionalChaining() {
  93. return this.outputOptions.environment.optionalChaining;
  94. }
  95. supportsForOf() {
  96. return this.outputOptions.environment.forOf;
  97. }
  98. supportsDestructuring() {
  99. return this.outputOptions.environment.destructuring;
  100. }
  101. supportsBigIntLiteral() {
  102. return this.outputOptions.environment.bigIntLiteral;
  103. }
  104. supportsDynamicImport() {
  105. return this.outputOptions.environment.dynamicImport;
  106. }
  107. supportsEcmaScriptModuleSyntax() {
  108. return this.outputOptions.environment.module;
  109. }
  110. supportTemplateLiteral() {
  111. return this.outputOptions.environment.templateLiteral;
  112. }
  113. returningFunction(returnValue, args = "") {
  114. return this.supportsArrowFunction()
  115. ? `(${args}) => (${returnValue})`
  116. : `function(${args}) { return ${returnValue}; }`;
  117. }
  118. basicFunction(args, body) {
  119. return this.supportsArrowFunction()
  120. ? `(${args}) => {\n${Template.indent(body)}\n}`
  121. : `function(${args}) {\n${Template.indent(body)}\n}`;
  122. }
  123. /**
  124. * @param {Array<string|{expr: string}>} args args
  125. * @returns {string} result expression
  126. */
  127. concatenation(...args) {
  128. const len = args.length;
  129. if (len === 2) return this._es5Concatenation(args);
  130. if (len === 0) return '""';
  131. if (len === 1) {
  132. return typeof args[0] === "string"
  133. ? JSON.stringify(args[0])
  134. : `"" + ${args[0].expr}`;
  135. }
  136. if (!this.supportTemplateLiteral()) return this._es5Concatenation(args);
  137. // cost comparison between template literal and concatenation:
  138. // both need equal surroundings: `xxx` vs "xxx"
  139. // template literal has constant cost of 3 chars for each expression
  140. // es5 concatenation has cost of 3 + n chars for n expressions in row
  141. // when a es5 concatenation ends with an expression it reduces cost by 3
  142. // when a es5 concatenation starts with an single expression it reduces cost by 3
  143. // e. g. `${a}${b}${c}` (3*3 = 9) is longer than ""+a+b+c ((3+3)-3 = 3)
  144. // 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)
  145. let templateCost = 0;
  146. let concatenationCost = 0;
  147. let lastWasExpr = false;
  148. for (const arg of args) {
  149. const isExpr = typeof arg !== "string";
  150. if (isExpr) {
  151. templateCost += 3;
  152. concatenationCost += lastWasExpr ? 1 : 4;
  153. }
  154. lastWasExpr = isExpr;
  155. }
  156. if (lastWasExpr) concatenationCost -= 3;
  157. if (typeof args[0] !== "string" && typeof args[1] === "string")
  158. concatenationCost -= 3;
  159. if (concatenationCost <= templateCost) return this._es5Concatenation(args);
  160. return `\`${args
  161. .map(arg => (typeof arg === "string" ? arg : `\${${arg.expr}}`))
  162. .join("")}\``;
  163. }
  164. /**
  165. * @param {Array<string|{expr: string}>} args args (len >= 2)
  166. * @returns {string} result expression
  167. * @private
  168. */
  169. _es5Concatenation(args) {
  170. const str = args
  171. .map(arg => (typeof arg === "string" ? JSON.stringify(arg) : arg.expr))
  172. .join(" + ");
  173. // when the first two args are expression, we need to prepend "" + to force string
  174. // concatenation instead of number addition.
  175. return typeof args[0] !== "string" && typeof args[1] !== "string"
  176. ? `"" + ${str}`
  177. : str;
  178. }
  179. expressionFunction(expression, args = "") {
  180. return this.supportsArrowFunction()
  181. ? `(${args}) => (${expression})`
  182. : `function(${args}) { ${expression}; }`;
  183. }
  184. emptyFunction() {
  185. return this.supportsArrowFunction() ? "x => {}" : "function() {}";
  186. }
  187. destructureArray(items, value) {
  188. return this.supportsDestructuring()
  189. ? `var [${items.join(", ")}] = ${value};`
  190. : Template.asString(
  191. items.map((item, i) => `var ${item} = ${value}[${i}];`)
  192. );
  193. }
  194. destructureObject(items, value) {
  195. return this.supportsDestructuring()
  196. ? `var {${items.join(", ")}} = ${value};`
  197. : Template.asString(
  198. items.map(item => `var ${item} = ${value}${propertyAccess([item])};`)
  199. );
  200. }
  201. iife(args, body) {
  202. return `(${this.basicFunction(args, body)})()`;
  203. }
  204. forEach(variable, array, body) {
  205. return this.supportsForOf()
  206. ? `for(const ${variable} of ${array}) {\n${Template.indent(body)}\n}`
  207. : `${array}.forEach(function(${variable}) {\n${Template.indent(
  208. body
  209. )}\n});`;
  210. }
  211. /**
  212. * Add a comment
  213. * @param {object} options Information content of the comment
  214. * @param {string=} options.request request string used originally
  215. * @param {string=} options.chunkName name of the chunk referenced
  216. * @param {string=} options.chunkReason reason information of the chunk
  217. * @param {string=} options.message additional message
  218. * @param {string=} options.exportName name of the export
  219. * @returns {string} comment
  220. */
  221. comment({ request, chunkName, chunkReason, message, exportName }) {
  222. let content;
  223. if (this.outputOptions.pathinfo) {
  224. content = [message, request, chunkName, chunkReason]
  225. .filter(Boolean)
  226. .map(item => this.requestShortener.shorten(item))
  227. .join(" | ");
  228. } else {
  229. content = [message, chunkName, chunkReason]
  230. .filter(Boolean)
  231. .map(item => this.requestShortener.shorten(item))
  232. .join(" | ");
  233. }
  234. if (!content) return "";
  235. if (this.outputOptions.pathinfo) {
  236. return Template.toComment(content) + " ";
  237. } else {
  238. return Template.toNormalComment(content) + " ";
  239. }
  240. }
  241. /**
  242. * @param {object} options generation options
  243. * @param {string=} options.request request string used originally
  244. * @returns {string} generated error block
  245. */
  246. throwMissingModuleErrorBlock({ request }) {
  247. const err = `Cannot find module '${request}'`;
  248. return `var e = new Error(${JSON.stringify(
  249. err
  250. )}); e.code = 'MODULE_NOT_FOUND'; throw e;`;
  251. }
  252. /**
  253. * @param {object} options generation options
  254. * @param {string=} options.request request string used originally
  255. * @returns {string} generated error function
  256. */
  257. throwMissingModuleErrorFunction({ request }) {
  258. return `function webpackMissingModule() { ${this.throwMissingModuleErrorBlock(
  259. { request }
  260. )} }`;
  261. }
  262. /**
  263. * @param {object} options generation options
  264. * @param {string=} options.request request string used originally
  265. * @returns {string} generated error IIFE
  266. */
  267. missingModule({ request }) {
  268. return `Object(${this.throwMissingModuleErrorFunction({ request })}())`;
  269. }
  270. /**
  271. * @param {object} options generation options
  272. * @param {string=} options.request request string used originally
  273. * @returns {string} generated error statement
  274. */
  275. missingModuleStatement({ request }) {
  276. return `${this.missingModule({ request })};\n`;
  277. }
  278. /**
  279. * @param {object} options generation options
  280. * @param {string=} options.request request string used originally
  281. * @returns {string} generated error code
  282. */
  283. missingModulePromise({ request }) {
  284. return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({
  285. request
  286. })})`;
  287. }
  288. /**
  289. * @param {Object} options options object
  290. * @param {ChunkGraph} options.chunkGraph the chunk graph
  291. * @param {Module} options.module the module
  292. * @param {string} options.request the request that should be printed as comment
  293. * @param {string=} options.idExpr expression to use as id expression
  294. * @param {"expression" | "promise" | "statements"} options.type which kind of code should be returned
  295. * @returns {string} the code
  296. */
  297. weakError({ module, chunkGraph, request, idExpr, type }) {
  298. const moduleId = chunkGraph.getModuleId(module);
  299. const errorMessage =
  300. moduleId === null
  301. ? JSON.stringify("Module is not available (weak dependency)")
  302. : idExpr
  303. ? `"Module '" + ${idExpr} + "' is not available (weak dependency)"`
  304. : JSON.stringify(
  305. `Module '${moduleId}' is not available (weak dependency)`
  306. );
  307. const comment = request ? Template.toNormalComment(request) + " " : "";
  308. const errorStatements =
  309. `var e = new Error(${errorMessage}); ` +
  310. comment +
  311. "e.code = 'MODULE_NOT_FOUND'; throw e;";
  312. switch (type) {
  313. case "statements":
  314. return errorStatements;
  315. case "promise":
  316. return `Promise.resolve().then(${this.basicFunction(
  317. "",
  318. errorStatements
  319. )})`;
  320. case "expression":
  321. return this.iife("", errorStatements);
  322. }
  323. }
  324. /**
  325. * @param {Object} options options object
  326. * @param {Module} options.module the module
  327. * @param {ChunkGraph} options.chunkGraph the chunk graph
  328. * @param {string} options.request the request that should be printed as comment
  329. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  330. * @returns {string} the expression
  331. */
  332. moduleId({ module, chunkGraph, request, weak }) {
  333. if (!module) {
  334. return this.missingModule({
  335. request
  336. });
  337. }
  338. const moduleId = chunkGraph.getModuleId(module);
  339. if (moduleId === null) {
  340. if (weak) {
  341. return "null /* weak dependency, without id */";
  342. }
  343. throw new Error(
  344. `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage(
  345. module,
  346. chunkGraph
  347. )}`
  348. );
  349. }
  350. return `${this.comment({ request })}${JSON.stringify(moduleId)}`;
  351. }
  352. /**
  353. * @param {Object} options options object
  354. * @param {Module} options.module the module
  355. * @param {ChunkGraph} options.chunkGraph the chunk graph
  356. * @param {string} options.request the request that should be printed as comment
  357. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  358. * @param {Set<string>} options.runtimeRequirements if set, will be filled with runtime requirements
  359. * @returns {string} the expression
  360. */
  361. moduleRaw({ module, chunkGraph, request, weak, runtimeRequirements }) {
  362. if (!module) {
  363. return this.missingModule({
  364. request
  365. });
  366. }
  367. const moduleId = chunkGraph.getModuleId(module);
  368. if (moduleId === null) {
  369. if (weak) {
  370. // only weak referenced modules don't get an id
  371. // we can always emit an error emitting code here
  372. return this.weakError({
  373. module,
  374. chunkGraph,
  375. request,
  376. type: "expression"
  377. });
  378. }
  379. throw new Error(
  380. `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage(
  381. module,
  382. chunkGraph
  383. )}`
  384. );
  385. }
  386. runtimeRequirements.add(RuntimeGlobals.require);
  387. return `__webpack_require__(${this.moduleId({
  388. module,
  389. chunkGraph,
  390. request,
  391. weak
  392. })})`;
  393. }
  394. /**
  395. * @param {Object} options options object
  396. * @param {Module} options.module the module
  397. * @param {ChunkGraph} options.chunkGraph the chunk graph
  398. * @param {string} options.request the request that should be printed as comment
  399. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  400. * @param {Set<string>} options.runtimeRequirements if set, will be filled with runtime requirements
  401. * @returns {string} the expression
  402. */
  403. moduleExports({ module, chunkGraph, request, weak, runtimeRequirements }) {
  404. return this.moduleRaw({
  405. module,
  406. chunkGraph,
  407. request,
  408. weak,
  409. runtimeRequirements
  410. });
  411. }
  412. /**
  413. * @param {Object} options options object
  414. * @param {Module} options.module the module
  415. * @param {ChunkGraph} options.chunkGraph the chunk graph
  416. * @param {string} options.request the request that should be printed as comment
  417. * @param {boolean=} options.strict if the current module is in strict esm mode
  418. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  419. * @param {Set<string>} options.runtimeRequirements if set, will be filled with runtime requirements
  420. * @returns {string} the expression
  421. */
  422. moduleNamespace({
  423. module,
  424. chunkGraph,
  425. request,
  426. strict,
  427. weak,
  428. runtimeRequirements
  429. }) {
  430. if (!module) {
  431. return this.missingModule({
  432. request
  433. });
  434. }
  435. if (chunkGraph.getModuleId(module) === null) {
  436. if (weak) {
  437. // only weak referenced modules don't get an id
  438. // we can always emit an error emitting code here
  439. return this.weakError({
  440. module,
  441. chunkGraph,
  442. request,
  443. type: "expression"
  444. });
  445. }
  446. throw new Error(
  447. `RuntimeTemplate.moduleNamespace(): ${noModuleIdErrorMessage(
  448. module,
  449. chunkGraph
  450. )}`
  451. );
  452. }
  453. const moduleId = this.moduleId({
  454. module,
  455. chunkGraph,
  456. request,
  457. weak
  458. });
  459. const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict);
  460. switch (exportsType) {
  461. case "namespace":
  462. return this.moduleRaw({
  463. module,
  464. chunkGraph,
  465. request,
  466. weak,
  467. runtimeRequirements
  468. });
  469. case "default-with-named":
  470. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  471. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 3)`;
  472. case "default-only":
  473. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  474. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 1)`;
  475. case "dynamic":
  476. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  477. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 7)`;
  478. }
  479. }
  480. /**
  481. * @param {Object} options options object
  482. * @param {ChunkGraph} options.chunkGraph the chunk graph
  483. * @param {AsyncDependenciesBlock=} options.block the current dependencies block
  484. * @param {Module} options.module the module
  485. * @param {string} options.request the request that should be printed as comment
  486. * @param {string} options.message a message for the comment
  487. * @param {boolean=} options.strict if the current module is in strict esm mode
  488. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  489. * @param {Set<string>} options.runtimeRequirements if set, will be filled with runtime requirements
  490. * @returns {string} the promise expression
  491. */
  492. moduleNamespacePromise({
  493. chunkGraph,
  494. block,
  495. module,
  496. request,
  497. message,
  498. strict,
  499. weak,
  500. runtimeRequirements
  501. }) {
  502. if (!module) {
  503. return this.missingModulePromise({
  504. request
  505. });
  506. }
  507. const moduleId = chunkGraph.getModuleId(module);
  508. if (moduleId === null) {
  509. if (weak) {
  510. // only weak referenced modules don't get an id
  511. // we can always emit an error emitting code here
  512. return this.weakError({
  513. module,
  514. chunkGraph,
  515. request,
  516. type: "promise"
  517. });
  518. }
  519. throw new Error(
  520. `RuntimeTemplate.moduleNamespacePromise(): ${noModuleIdErrorMessage(
  521. module,
  522. chunkGraph
  523. )}`
  524. );
  525. }
  526. const promise = this.blockPromise({
  527. chunkGraph,
  528. block,
  529. message,
  530. runtimeRequirements
  531. });
  532. let appending;
  533. let idExpr = JSON.stringify(chunkGraph.getModuleId(module));
  534. const comment = this.comment({
  535. request
  536. });
  537. let header = "";
  538. if (weak) {
  539. if (idExpr.length > 8) {
  540. // 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"'
  541. header += `var id = ${idExpr}; `;
  542. idExpr = "id";
  543. }
  544. runtimeRequirements.add(RuntimeGlobals.moduleFactories);
  545. header += `if(!${
  546. RuntimeGlobals.moduleFactories
  547. }[${idExpr}]) { ${this.weakError({
  548. module,
  549. chunkGraph,
  550. request,
  551. idExpr,
  552. type: "statements"
  553. })} } `;
  554. }
  555. const moduleIdExpr = this.moduleId({
  556. module,
  557. chunkGraph,
  558. request,
  559. weak
  560. });
  561. const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict);
  562. let fakeType = 16;
  563. switch (exportsType) {
  564. case "namespace":
  565. if (header) {
  566. const rawModule = this.moduleRaw({
  567. module,
  568. chunkGraph,
  569. request,
  570. weak,
  571. runtimeRequirements
  572. });
  573. appending = `.then(${this.basicFunction(
  574. "",
  575. `${header}return ${rawModule};`
  576. )})`;
  577. } else {
  578. runtimeRequirements.add(RuntimeGlobals.require);
  579. appending = `.then(__webpack_require__.bind(__webpack_require__, ${comment}${idExpr}))`;
  580. }
  581. break;
  582. case "dynamic":
  583. fakeType |= 4;
  584. /* fall through */
  585. case "default-with-named":
  586. fakeType |= 2;
  587. /* fall through */
  588. case "default-only":
  589. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  590. if (chunkGraph.moduleGraph.isAsync(module)) {
  591. if (header) {
  592. const rawModule = this.moduleRaw({
  593. module,
  594. chunkGraph,
  595. request,
  596. weak,
  597. runtimeRequirements
  598. });
  599. appending = `.then(${this.basicFunction(
  600. "",
  601. `${header}return ${rawModule};`
  602. )})`;
  603. } else {
  604. runtimeRequirements.add(RuntimeGlobals.require);
  605. appending = `.then(__webpack_require__.bind(__webpack_require__, ${comment}${idExpr}))`;
  606. }
  607. appending += `.then(${this.returningFunction(
  608. `${RuntimeGlobals.createFakeNamespaceObject}(m, ${fakeType})`,
  609. "m"
  610. )})`;
  611. } else {
  612. fakeType |= 1;
  613. if (header) {
  614. const returnExpression = `${RuntimeGlobals.createFakeNamespaceObject}(${moduleIdExpr}, ${fakeType})`;
  615. appending = `.then(${this.basicFunction(
  616. "",
  617. `${header}return ${returnExpression};`
  618. )})`;
  619. } else {
  620. appending = `.then(${RuntimeGlobals.createFakeNamespaceObject}.bind(__webpack_require__, ${comment}${idExpr}, ${fakeType}))`;
  621. }
  622. }
  623. break;
  624. }
  625. return `${promise || "Promise.resolve()"}${appending}`;
  626. }
  627. /**
  628. * @param {Object} options options object
  629. * @param {ChunkGraph} options.chunkGraph the chunk graph
  630. * @param {RuntimeSpec=} options.runtime runtime for which this code will be generated
  631. * @param {RuntimeSpec | boolean=} options.runtimeCondition only execute the statement in some runtimes
  632. * @param {Set<string>} options.runtimeRequirements if set, will be filled with runtime requirements
  633. * @returns {string} expression
  634. */
  635. runtimeConditionExpression({
  636. chunkGraph,
  637. runtimeCondition,
  638. runtime,
  639. runtimeRequirements
  640. }) {
  641. if (runtimeCondition === undefined) return "true";
  642. if (typeof runtimeCondition === "boolean") return `${runtimeCondition}`;
  643. /** @type {Set<string>} */
  644. const positiveRuntimeIds = new Set();
  645. forEachRuntime(runtimeCondition, runtime =>
  646. positiveRuntimeIds.add(`${chunkGraph.getRuntimeId(runtime)}`)
  647. );
  648. /** @type {Set<string>} */
  649. const negativeRuntimeIds = new Set();
  650. forEachRuntime(subtractRuntime(runtime, runtimeCondition), runtime =>
  651. negativeRuntimeIds.add(`${chunkGraph.getRuntimeId(runtime)}`)
  652. );
  653. runtimeRequirements.add(RuntimeGlobals.runtimeId);
  654. return compileBooleanMatcher.fromLists(
  655. Array.from(positiveRuntimeIds),
  656. Array.from(negativeRuntimeIds)
  657. )(RuntimeGlobals.runtimeId);
  658. }
  659. /**
  660. *
  661. * @param {Object} options options object
  662. * @param {boolean=} options.update whether a new variable should be created or the existing one updated
  663. * @param {Module} options.module the module
  664. * @param {ChunkGraph} options.chunkGraph the chunk graph
  665. * @param {string} options.request the request that should be printed as comment
  666. * @param {string} options.importVar name of the import variable
  667. * @param {Module} options.originModule module in which the statement is emitted
  668. * @param {boolean=} options.weak true, if this is a weak dependency
  669. * @param {Set<string>} options.runtimeRequirements if set, will be filled with runtime requirements
  670. * @returns {[string, string]} the import statement and the compat statement
  671. */
  672. importStatement({
  673. update,
  674. module,
  675. chunkGraph,
  676. request,
  677. importVar,
  678. originModule,
  679. weak,
  680. runtimeRequirements
  681. }) {
  682. if (!module) {
  683. return [
  684. this.missingModuleStatement({
  685. request
  686. }),
  687. ""
  688. ];
  689. }
  690. if (chunkGraph.getModuleId(module) === null) {
  691. if (weak) {
  692. // only weak referenced modules don't get an id
  693. // we can always emit an error emitting code here
  694. return [
  695. this.weakError({
  696. module,
  697. chunkGraph,
  698. request,
  699. type: "statements"
  700. }),
  701. ""
  702. ];
  703. }
  704. throw new Error(
  705. `RuntimeTemplate.importStatement(): ${noModuleIdErrorMessage(
  706. module,
  707. chunkGraph
  708. )}`
  709. );
  710. }
  711. const moduleId = this.moduleId({
  712. module,
  713. chunkGraph,
  714. request,
  715. weak
  716. });
  717. const optDeclaration = update ? "" : "var ";
  718. const exportsType = module.getExportsType(
  719. chunkGraph.moduleGraph,
  720. originModule.buildMeta.strictHarmonyModule
  721. );
  722. runtimeRequirements.add(RuntimeGlobals.require);
  723. const importContent = `/* harmony import */ ${optDeclaration}${importVar} = __webpack_require__(${moduleId});\n`;
  724. if (exportsType === "dynamic") {
  725. runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport);
  726. return [
  727. importContent,
  728. `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${importVar});\n`
  729. ];
  730. }
  731. return [importContent, ""];
  732. }
  733. /**
  734. * @param {Object} options options
  735. * @param {ModuleGraph} options.moduleGraph the module graph
  736. * @param {Module} options.module the module
  737. * @param {string} options.request the request
  738. * @param {string | string[]} options.exportName the export name
  739. * @param {Module} options.originModule the origin module
  740. * @param {boolean|undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted
  741. * @param {boolean} options.isCall true, if expression will be called
  742. * @param {boolean} options.callContext when false, call context will not be preserved
  743. * @param {boolean} options.defaultInterop when true and accessing the default exports, interop code will be generated
  744. * @param {string} options.importVar the identifier name of the import variable
  745. * @param {InitFragment[]} options.initFragments init fragments will be added here
  746. * @param {RuntimeSpec} options.runtime runtime for which this code will be generated
  747. * @param {Set<string>} options.runtimeRequirements if set, will be filled with runtime requirements
  748. * @returns {string} expression
  749. */
  750. exportFromImport({
  751. moduleGraph,
  752. module,
  753. request,
  754. exportName,
  755. originModule,
  756. asiSafe,
  757. isCall,
  758. callContext,
  759. defaultInterop,
  760. importVar,
  761. initFragments,
  762. runtime,
  763. runtimeRequirements
  764. }) {
  765. if (!module) {
  766. return this.missingModule({
  767. request
  768. });
  769. }
  770. if (!Array.isArray(exportName)) {
  771. exportName = exportName ? [exportName] : [];
  772. }
  773. const exportsType = module.getExportsType(
  774. moduleGraph,
  775. originModule.buildMeta.strictHarmonyModule
  776. );
  777. if (defaultInterop) {
  778. if (exportName.length > 0 && exportName[0] === "default") {
  779. switch (exportsType) {
  780. case "dynamic":
  781. if (isCall) {
  782. return `${importVar}_default()${propertyAccess(exportName, 1)}`;
  783. } else {
  784. return asiSafe
  785. ? `(${importVar}_default()${propertyAccess(exportName, 1)})`
  786. : asiSafe === false
  787. ? `;(${importVar}_default()${propertyAccess(exportName, 1)})`
  788. : `${importVar}_default.a${propertyAccess(exportName, 1)}`;
  789. }
  790. case "default-only":
  791. case "default-with-named":
  792. exportName = exportName.slice(1);
  793. break;
  794. }
  795. } else if (exportName.length > 0) {
  796. if (exportsType === "default-only") {
  797. return (
  798. "/* non-default import from non-esm module */undefined" +
  799. propertyAccess(exportName, 1)
  800. );
  801. } else if (
  802. exportsType !== "namespace" &&
  803. exportName[0] === "__esModule"
  804. ) {
  805. return "/* __esModule */true";
  806. }
  807. } else if (
  808. exportsType === "default-only" ||
  809. exportsType === "default-with-named"
  810. ) {
  811. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  812. initFragments.push(
  813. new InitFragment(
  814. `var ${importVar}_namespace_cache;\n`,
  815. InitFragment.STAGE_CONSTANTS,
  816. -1,
  817. `${importVar}_namespace_cache`
  818. )
  819. );
  820. return `/*#__PURE__*/ ${
  821. asiSafe ? "" : asiSafe === false ? ";" : "Object"
  822. }(${importVar}_namespace_cache || (${importVar}_namespace_cache = ${
  823. RuntimeGlobals.createFakeNamespaceObject
  824. }(${importVar}${exportsType === "default-only" ? "" : ", 2"})))`;
  825. }
  826. }
  827. if (exportName.length > 0) {
  828. const exportsInfo = moduleGraph.getExportsInfo(module);
  829. const used = exportsInfo.getUsedName(exportName, runtime);
  830. if (!used) {
  831. const comment = Template.toNormalComment(
  832. `unused export ${propertyAccess(exportName)}`
  833. );
  834. return `${comment} undefined`;
  835. }
  836. const comment = equals(used, exportName)
  837. ? ""
  838. : Template.toNormalComment(propertyAccess(exportName)) + " ";
  839. const access = `${importVar}${comment}${propertyAccess(used)}`;
  840. if (isCall && callContext === false) {
  841. return asiSafe
  842. ? `(0,${access})`
  843. : asiSafe === false
  844. ? `;(0,${access})`
  845. : `/*#__PURE__*/Object(${access})`;
  846. }
  847. return access;
  848. } else {
  849. return importVar;
  850. }
  851. }
  852. /**
  853. * @param {Object} options options
  854. * @param {AsyncDependenciesBlock} options.block the async block
  855. * @param {string} options.message the message
  856. * @param {ChunkGraph} options.chunkGraph the chunk graph
  857. * @param {Set<string>} options.runtimeRequirements if set, will be filled with runtime requirements
  858. * @returns {string} expression
  859. */
  860. blockPromise({ block, message, chunkGraph, runtimeRequirements }) {
  861. if (!block) {
  862. const comment = this.comment({
  863. message
  864. });
  865. return `Promise.resolve(${comment.trim()})`;
  866. }
  867. const chunkGroup = chunkGraph.getBlockChunkGroup(block);
  868. if (!chunkGroup || chunkGroup.chunks.length === 0) {
  869. const comment = this.comment({
  870. message
  871. });
  872. return `Promise.resolve(${comment.trim()})`;
  873. }
  874. const chunks = chunkGroup.chunks.filter(
  875. chunk => !chunk.hasRuntime() && chunk.id !== null
  876. );
  877. const comment = this.comment({
  878. message,
  879. chunkName: block.chunkName
  880. });
  881. if (chunks.length === 1) {
  882. const chunkId = JSON.stringify(chunks[0].id);
  883. runtimeRequirements.add(RuntimeGlobals.ensureChunk);
  884. return `${RuntimeGlobals.ensureChunk}(${comment}${chunkId})`;
  885. } else if (chunks.length > 0) {
  886. runtimeRequirements.add(RuntimeGlobals.ensureChunk);
  887. const requireChunkId = chunk =>
  888. `${RuntimeGlobals.ensureChunk}(${JSON.stringify(chunk.id)})`;
  889. return `Promise.all(${comment.trim()}[${chunks
  890. .map(requireChunkId)
  891. .join(", ")}])`;
  892. } else {
  893. return `Promise.resolve(${comment.trim()})`;
  894. }
  895. }
  896. /**
  897. * @param {Object} options options
  898. * @param {AsyncDependenciesBlock} options.block the async block
  899. * @param {ChunkGraph} options.chunkGraph the chunk graph
  900. * @param {Set<string>} options.runtimeRequirements if set, will be filled with runtime requirements
  901. * @param {string=} options.request request string used originally
  902. * @returns {string} expression
  903. */
  904. asyncModuleFactory({ block, chunkGraph, runtimeRequirements, request }) {
  905. const dep = block.dependencies[0];
  906. const module = chunkGraph.moduleGraph.getModule(dep);
  907. const ensureChunk = this.blockPromise({
  908. block,
  909. message: "",
  910. chunkGraph,
  911. runtimeRequirements
  912. });
  913. const factory = this.returningFunction(
  914. this.moduleRaw({
  915. module,
  916. chunkGraph,
  917. request,
  918. runtimeRequirements
  919. })
  920. );
  921. return this.returningFunction(
  922. ensureChunk.startsWith("Promise.resolve(")
  923. ? `${factory}`
  924. : `${ensureChunk}.then(${this.returningFunction(factory)})`
  925. );
  926. }
  927. /**
  928. * @param {Object} options options
  929. * @param {Dependency} options.dependency the dependency
  930. * @param {ChunkGraph} options.chunkGraph the chunk graph
  931. * @param {Set<string>} options.runtimeRequirements if set, will be filled with runtime requirements
  932. * @param {string=} options.request request string used originally
  933. * @returns {string} expression
  934. */
  935. syncModuleFactory({ dependency, chunkGraph, runtimeRequirements, request }) {
  936. const module = chunkGraph.moduleGraph.getModule(dependency);
  937. const factory = this.returningFunction(
  938. this.moduleRaw({
  939. module,
  940. chunkGraph,
  941. request,
  942. runtimeRequirements
  943. })
  944. );
  945. return this.returningFunction(factory);
  946. }
  947. /**
  948. * @param {Object} options options
  949. * @param {string} options.exportsArgument the name of the exports object
  950. * @param {Set<string>} options.runtimeRequirements if set, will be filled with runtime requirements
  951. * @returns {string} statement
  952. */
  953. defineEsModuleFlagStatement({ exportsArgument, runtimeRequirements }) {
  954. runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject);
  955. runtimeRequirements.add(RuntimeGlobals.exports);
  956. return `${RuntimeGlobals.makeNamespaceObject}(${exportsArgument});\n`;
  957. }
  958. /**
  959. * @param {Object} options options object
  960. * @param {Module} options.module the module
  961. * @param {string} options.publicPath the public path
  962. * @param {RuntimeSpec=} options.runtime runtime
  963. * @param {CodeGenerationResults} options.codeGenerationResults the code generation results
  964. * @returns {string} the url of the asset
  965. */
  966. assetUrl({ publicPath, runtime, module, codeGenerationResults }) {
  967. if (!module) {
  968. return "data:,";
  969. }
  970. const codeGen = codeGenerationResults.get(module, runtime);
  971. const { data } = codeGen;
  972. const url = data.get("url");
  973. if (url) return url.toString();
  974. const filename = data.get("filename");
  975. return publicPath + filename;
  976. }
  977. }
  978. module.exports = RuntimeTemplate;