CssExportsGenerator.js 6.6 KB

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