AssetSourceGenerator.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Sergey Melyukov @smelukov
  4. */
  5. "use strict";
  6. const { RawSource } = require("webpack-sources");
  7. const ConcatenationScope = require("../ConcatenationScope");
  8. const Generator = require("../Generator");
  9. const {
  10. ASSET_URL_TYPE,
  11. ASSET_URL_TYPES,
  12. CSS_TYPE,
  13. HTML_TYPE,
  14. JAVASCRIPT_AND_ASSET_URL_TYPES,
  15. JAVASCRIPT_TYPE,
  16. JAVASCRIPT_TYPES,
  17. NO_TYPES
  18. } = require("../ModuleSourceTypeConstants");
  19. const RuntimeGlobals = require("../RuntimeGlobals");
  20. const { languageOfFilename } = require("../util/dataURL");
  21. /** @import { Source } from "webpack-sources" */
  22. /** @import { GenerateContext, UpdateHashContext } from "../Generator" */
  23. /** @import Hash from "../util/Hash" */
  24. /**
  25. * @import {
  26. * ConcatenationBailoutReasonContext,
  27. * SourceType,
  28. * SourceTypes
  29. * } from "../Module"
  30. */
  31. /** @import ModuleGraph from "../ModuleGraph" */
  32. /** @import NormalModule from "../NormalModule" */
  33. class AssetSourceGenerator extends Generator {
  34. /**
  35. * Creates an instance of AssetSourceGenerator.
  36. * @param {ModuleGraph} moduleGraph the module graph
  37. */
  38. constructor(moduleGraph) {
  39. super();
  40. /** @type {ModuleGraph} */
  41. this._moduleGraph = moduleGraph;
  42. }
  43. /**
  44. * Generates generated code for this runtime module.
  45. * @param {NormalModule} module module for which the code should be generated
  46. * @param {GenerateContext} generateContext context for generate
  47. * @returns {Source | null} generated code
  48. */
  49. generate(
  50. module,
  51. { type, concatenationScope, getData, runtimeTemplate, runtimeRequirements }
  52. ) {
  53. const originalSource = module.originalSource();
  54. const data = getData ? getData() : undefined;
  55. switch (type) {
  56. case JAVASCRIPT_TYPE: {
  57. if (!originalSource) {
  58. return new RawSource("");
  59. }
  60. const content = originalSource.source();
  61. const encodedSource = AssetSourceGenerator._renderEmbedded(
  62. module,
  63. typeof content === "string" ? content : content.toString("utf8"),
  64. runtimeTemplate
  65. );
  66. /** @type {string} */
  67. let sourceContent;
  68. if (concatenationScope) {
  69. concatenationScope.registerNamespaceExport(
  70. ConcatenationScope.NAMESPACE_OBJECT_EXPORT
  71. );
  72. sourceContent = `${runtimeTemplate.renderConst()} ${
  73. ConcatenationScope.NAMESPACE_OBJECT_EXPORT
  74. } = ${JSON.stringify(encodedSource)};`;
  75. } else {
  76. runtimeRequirements.add(RuntimeGlobals.module);
  77. sourceContent = `${module.moduleArgument}.exports = ${JSON.stringify(
  78. encodedSource
  79. )};`;
  80. }
  81. return new RawSource(sourceContent);
  82. }
  83. case ASSET_URL_TYPE: {
  84. if (!originalSource) {
  85. return null;
  86. }
  87. const content = originalSource.source();
  88. const encodedSource =
  89. typeof content === "string" ? content : content.toString("utf8");
  90. if (data) {
  91. data.set("url", { [type]: encodedSource });
  92. }
  93. return null;
  94. }
  95. default:
  96. return null;
  97. }
  98. }
  99. /**
  100. * Offer the file's text to `renderEmbeddedSource` before it is embedded in
  101. * JavaScript. Declines a file whose name names no language webpack knows.
  102. * @param {NormalModule} module the module holding the text
  103. * @param {string} text the file's text
  104. * @param {GenerateContext["runtimeTemplate"]} runtimeTemplate runtime template
  105. * @returns {string} the rendered text, or `text` when nothing rendered it
  106. */
  107. static _renderEmbedded(module, text, runtimeTemplate) {
  108. if (!runtimeTemplate) return text;
  109. // Untapped, nothing can change: no mime lookup and no source to wrap.
  110. const { compilation } = runtimeTemplate;
  111. if (compilation.hooks.renderEmbeddedSource.taps.length === 0) return text;
  112. const type = languageOfFilename(module.nameForCondition());
  113. if (type === undefined) return text;
  114. const rendered = compilation._resolveEmbeddedSource(new RawSource(text), {
  115. type,
  116. hostType: JAVASCRIPT_TYPE,
  117. module
  118. });
  119. return /** @type {string} */ (rendered.source());
  120. }
  121. /**
  122. * Updates the hash with the data contributed by this instance.
  123. * @param {Hash} hash hash that will be modified
  124. * @param {UpdateHashContext} updateHashContext context for updating hash
  125. */
  126. updateHash(hash, updateHashContext) {
  127. const { module, runtimeTemplate } = updateHashContext;
  128. // What a tap varies on has to reach the key, or a changed option replays.
  129. if (
  130. runtimeTemplate &&
  131. runtimeTemplate.compilation.hooks.renderEmbeddedSource.taps.length > 0 &&
  132. languageOfFilename(module.nameForCondition())
  133. ) {
  134. runtimeTemplate.compilation.hooks.embeddedSourceHash.call(module, hash);
  135. }
  136. }
  137. /**
  138. * Generates fallback output for the provided error condition.
  139. * @param {Error} error the error
  140. * @param {NormalModule} module module for which the code should be generated
  141. * @param {GenerateContext} generateContext context for generate
  142. * @returns {Source | null} generated code
  143. */
  144. generateError(error, module, generateContext) {
  145. switch (generateContext.type) {
  146. case JAVASCRIPT_TYPE: {
  147. return new RawSource(Generator.throwBuildErrorCode(error));
  148. }
  149. default:
  150. return null;
  151. }
  152. }
  153. /**
  154. * Returns the reason this module cannot be concatenated, when one exists.
  155. * @param {NormalModule} module module for which the bailout reason should be determined
  156. * @param {ConcatenationBailoutReasonContext} context context
  157. * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
  158. */
  159. getConcatenationBailoutReason(module, context) {
  160. return undefined;
  161. }
  162. /**
  163. * Returns the source types available for this module.
  164. * @param {NormalModule} module fresh module
  165. * @returns {SourceTypes} available types (do not mutate)
  166. */
  167. getTypes(module) {
  168. /** @type {Set<string>} */
  169. const sourceTypes = new Set();
  170. const connections = this._moduleGraph.getIncomingConnections(module);
  171. for (const connection of connections) {
  172. if (!connection.originModule) {
  173. continue;
  174. }
  175. sourceTypes.add(connection.originModule.type.split("/")[0]);
  176. }
  177. if (sourceTypes.size > 0) {
  178. if (
  179. sourceTypes.has(JAVASCRIPT_TYPE) &&
  180. (sourceTypes.has(CSS_TYPE) || sourceTypes.has(HTML_TYPE))
  181. ) {
  182. return JAVASCRIPT_AND_ASSET_URL_TYPES;
  183. } else if (sourceTypes.has(CSS_TYPE) || sourceTypes.has(HTML_TYPE)) {
  184. return ASSET_URL_TYPES;
  185. }
  186. return JAVASCRIPT_TYPES;
  187. }
  188. return NO_TYPES;
  189. }
  190. /**
  191. * @returns {boolean} whether getTypes() depends on the module's incoming connections
  192. */
  193. getTypesDependOnIncomingConnections() {
  194. return true;
  195. }
  196. /**
  197. * Returns the estimated size for the requested source type.
  198. * @param {NormalModule} module the module
  199. * @param {SourceType=} type source type
  200. * @returns {number} estimate size of the module
  201. */
  202. getSize(module, type) {
  203. const originalSource = module.originalSource();
  204. if (!originalSource) {
  205. return 0;
  206. }
  207. // Example: m.exports="abcd"
  208. return originalSource.size() + 12;
  209. }
  210. }
  211. module.exports = AssetSourceGenerator;