CssExportsGenerator.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Sergey Melyukov @smelukov
  4. */
  5. "use strict";
  6. const { ReplaceSource, RawSource, ConcatSource } = require("webpack-sources");
  7. const { UsageState } = require("../ExportsInfo");
  8. const Generator = require("../Generator");
  9. const RuntimeGlobals = require("../RuntimeGlobals");
  10. const Template = require("../Template");
  11. /** @typedef {import("webpack-sources").Source} Source */
  12. /** @typedef {import("../../declarations/WebpackOptions").CssGeneratorExportsConvention} CssGeneratorExportsConvention */
  13. /** @typedef {import("../../declarations/WebpackOptions").CssGeneratorLocalIdentName} CssGeneratorLocalIdentName */
  14. /** @typedef {import("../Dependency")} Dependency */
  15. /** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */
  16. /** @typedef {import("../DependencyTemplate").CssExportsData} CssExportsData */
  17. /** @typedef {import("../Generator").GenerateContext} GenerateContext */
  18. /** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */
  19. /** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
  20. /** @typedef {import("../NormalModule")} NormalModule */
  21. /** @typedef {import("../util/Hash")} Hash */
  22. /**
  23. * @template T
  24. * @typedef {import("../InitFragment")<T>} InitFragment
  25. */
  26. const TYPES = new Set(["javascript"]);
  27. class CssExportsGenerator extends Generator {
  28. /**
  29. * @param {CssGeneratorExportsConvention | undefined} convention the convention of the exports name
  30. * @param {CssGeneratorLocalIdentName | undefined} localIdentName css export local ident name
  31. * @param {boolean} esModule whether to use ES modules syntax
  32. */
  33. constructor(convention, localIdentName, esModule) {
  34. super();
  35. /** @type {CssGeneratorExportsConvention | undefined} */
  36. this.convention = convention;
  37. /** @type {CssGeneratorLocalIdentName | undefined} */
  38. this.localIdentName = localIdentName;
  39. /** @type {boolean} */
  40. this.esModule = esModule;
  41. }
  42. /**
  43. * @param {NormalModule} module module for which the bailout reason should be determined
  44. * @param {ConcatenationBailoutReasonContext} context context
  45. * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
  46. */
  47. getConcatenationBailoutReason(module, context) {
  48. if (!this.esModule) {
  49. return "Module is not an ECMAScript module";
  50. }
  51. // TODO webpack 6: remove /\[moduleid\]/.test
  52. if (
  53. /\[id\]/.test(this.localIdentName) ||
  54. /\[moduleid\]/.test(this.localIdentName)
  55. ) {
  56. return "The localIdentName includes moduleId ([id] or [moduleid])";
  57. }
  58. return undefined;
  59. }
  60. /**
  61. * @param {NormalModule} module module for which the code should be generated
  62. * @param {GenerateContext} generateContext context for generate
  63. * @returns {Source} generated code
  64. */
  65. generate(module, generateContext) {
  66. const source = new ReplaceSource(new RawSource(""));
  67. /** @type {InitFragment<TODO>[]} */
  68. const initFragments = [];
  69. /** @type {CssExportsData} */
  70. const cssExportsData = {
  71. esModule: this.esModule,
  72. exports: new Map()
  73. };
  74. generateContext.runtimeRequirements.add(RuntimeGlobals.module);
  75. let chunkInitFragments;
  76. const runtimeRequirements = new Set();
  77. /** @type {DependencyTemplateContext} */
  78. const templateContext = {
  79. runtimeTemplate: generateContext.runtimeTemplate,
  80. dependencyTemplates: generateContext.dependencyTemplates,
  81. moduleGraph: generateContext.moduleGraph,
  82. chunkGraph: generateContext.chunkGraph,
  83. module,
  84. runtime: generateContext.runtime,
  85. runtimeRequirements: runtimeRequirements,
  86. concatenationScope: generateContext.concatenationScope,
  87. codeGenerationResults: generateContext.codeGenerationResults,
  88. initFragments,
  89. cssExportsData,
  90. get chunkInitFragments() {
  91. if (!chunkInitFragments) {
  92. const data = generateContext.getData();
  93. chunkInitFragments = data.get("chunkInitFragments");
  94. if (!chunkInitFragments) {
  95. chunkInitFragments = [];
  96. data.set("chunkInitFragments", chunkInitFragments);
  97. }
  98. }
  99. return chunkInitFragments;
  100. }
  101. };
  102. /**
  103. * @param {Dependency} dependency the dependency
  104. */
  105. const handleDependency = dependency => {
  106. const constructor = /** @type {new (...args: any[]) => Dependency} */ (
  107. dependency.constructor
  108. );
  109. const template = generateContext.dependencyTemplates.get(constructor);
  110. if (!template) {
  111. throw new Error(
  112. "No template for dependency: " + dependency.constructor.name
  113. );
  114. }
  115. template.apply(dependency, source, templateContext);
  116. };
  117. module.dependencies.forEach(handleDependency);
  118. if (generateContext.concatenationScope) {
  119. const source = new ConcatSource();
  120. const usedIdentifiers = new Set();
  121. for (const [name, v] of cssExportsData.exports) {
  122. let identifier = Template.toIdentifier(name);
  123. let i = 0;
  124. while (usedIdentifiers.has(identifier)) {
  125. identifier = Template.toIdentifier(name + i);
  126. }
  127. usedIdentifiers.add(identifier);
  128. generateContext.concatenationScope.registerExport(name, identifier);
  129. source.add(
  130. `${
  131. generateContext.runtimeTemplate.supportsConst() ? "const" : "var"
  132. } ${identifier} = ${JSON.stringify(v)};\n`
  133. );
  134. }
  135. return source;
  136. } else {
  137. const needNsObj =
  138. this.esModule &&
  139. generateContext.moduleGraph
  140. .getExportsInfo(module)
  141. .otherExportsInfo.getUsed(generateContext.runtime) !==
  142. UsageState.Unused;
  143. if (needNsObj) {
  144. generateContext.runtimeRequirements.add(
  145. RuntimeGlobals.makeNamespaceObject
  146. );
  147. }
  148. const exports = [];
  149. for (let [name, v] of cssExportsData.exports) {
  150. exports.push(`\t${JSON.stringify(name)}: ${JSON.stringify(v)}`);
  151. }
  152. return new RawSource(
  153. `${needNsObj ? `${RuntimeGlobals.makeNamespaceObject}(` : ""}${
  154. module.moduleArgument
  155. }.exports = {\n${exports.join(",\n")}\n}${needNsObj ? ")" : ""};`
  156. );
  157. }
  158. }
  159. /**
  160. * @param {NormalModule} module fresh module
  161. * @returns {Set<string>} available types (do not mutate)
  162. */
  163. getTypes(module) {
  164. return TYPES;
  165. }
  166. /**
  167. * @param {NormalModule} module the module
  168. * @param {string=} type source type
  169. * @returns {number} estimate size of the module
  170. */
  171. getSize(module, type) {
  172. return 42;
  173. }
  174. /**
  175. * @param {Hash} hash hash that will be modified
  176. * @param {UpdateHashContext} updateHashContext context for updating hash
  177. */
  178. updateHash(hash, { module }) {
  179. hash.update(this.esModule.toString());
  180. }
  181. }
  182. module.exports = CssExportsGenerator;