CssGenerator.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Sergey Melyukov @smelukov
  4. */
  5. "use strict";
  6. const { ConcatSource, RawSource, ReplaceSource } = require("webpack-sources");
  7. const { UsageState } = require("../ExportsInfo");
  8. const Generator = require("../Generator");
  9. const InitFragment = require("../InitFragment");
  10. const {
  11. CSS_TYPE,
  12. CSS_TYPES,
  13. JS_AND_CSS_EXPORT_TYPES,
  14. JS_AND_CSS_TYPES,
  15. JS_TYPE
  16. } = require("../ModuleSourceTypesConstants");
  17. const RuntimeGlobals = require("../RuntimeGlobals");
  18. const Template = require("../Template");
  19. const memoize = require("../util/memoize");
  20. /** @typedef {import("webpack-sources").Source} Source */
  21. /** @typedef {import("../../declarations/WebpackOptions").CssAutoGeneratorOptions} CssAutoGeneratorOptions */
  22. /** @typedef {import("../../declarations/WebpackOptions").CssGlobalGeneratorOptions} CssGlobalGeneratorOptions */
  23. /** @typedef {import("../../declarations/WebpackOptions").CssModuleGeneratorOptions} CssModuleGeneratorOptions */
  24. /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
  25. /** @typedef {import("../Dependency")} Dependency */
  26. /** @typedef {import("../DependencyTemplate").CssData} CssData */
  27. /** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */
  28. /** @typedef {import("../Generator").GenerateContext} GenerateContext */
  29. /** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */
  30. /** @typedef {import("../Module").BuildInfo} BuildInfo */
  31. /** @typedef {import("../Module").BuildMeta} BuildMeta */
  32. /** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
  33. /** @typedef {import("../Module").SourceTypes} SourceTypes */
  34. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  35. /** @typedef {import("../NormalModule")} NormalModule */
  36. /** @typedef {import("../util/Hash")} Hash */
  37. const getPropertyName = memoize(() => require("../util/propertyName"));
  38. class CssGenerator extends Generator {
  39. /**
  40. * @param {CssAutoGeneratorOptions | CssGlobalGeneratorOptions | CssModuleGeneratorOptions} options options
  41. * @param {ModuleGraph} moduleGraph the module graph
  42. */
  43. constructor(options, moduleGraph) {
  44. super();
  45. this.convention = options.exportsConvention;
  46. this.localIdentName = options.localIdentName;
  47. this.exportsOnly = options.exportsOnly;
  48. this.esModule = options.esModule;
  49. this._moduleGraph = moduleGraph;
  50. }
  51. /**
  52. * @param {NormalModule} module module for which the bailout reason should be determined
  53. * @param {ConcatenationBailoutReasonContext} context context
  54. * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
  55. */
  56. getConcatenationBailoutReason(module, context) {
  57. if (!this.esModule) {
  58. return "Module is not an ECMAScript module";
  59. }
  60. return undefined;
  61. }
  62. /**
  63. * @param {NormalModule} module module for which the code should be generated
  64. * @param {GenerateContext} generateContext context for generate
  65. * @returns {Source | null} generated code
  66. */
  67. generate(module, generateContext) {
  68. const source =
  69. generateContext.type === "javascript"
  70. ? new ReplaceSource(new RawSource(""))
  71. : new ReplaceSource(/** @type {Source} */ (module.originalSource()));
  72. /** @type {InitFragment<GenerateContext>[]} */
  73. const initFragments = [];
  74. /** @type {CssData} */
  75. const cssData = {
  76. esModule: /** @type {boolean} */ (this.esModule),
  77. exports: new Map()
  78. };
  79. /** @type {InitFragment<GenerateContext>[] | undefined} */
  80. let chunkInitFragments;
  81. /** @type {DependencyTemplateContext} */
  82. const templateContext = {
  83. runtimeTemplate: generateContext.runtimeTemplate,
  84. dependencyTemplates: generateContext.dependencyTemplates,
  85. moduleGraph: generateContext.moduleGraph,
  86. chunkGraph: generateContext.chunkGraph,
  87. module,
  88. runtime: generateContext.runtime,
  89. runtimeRequirements: generateContext.runtimeRequirements,
  90. concatenationScope: generateContext.concatenationScope,
  91. codeGenerationResults:
  92. /** @type {CodeGenerationResults} */
  93. (generateContext.codeGenerationResults),
  94. initFragments,
  95. cssData,
  96. get chunkInitFragments() {
  97. if (!chunkInitFragments) {
  98. const data =
  99. /** @type {NonNullable<GenerateContext["getData"]>} */
  100. (generateContext.getData)();
  101. chunkInitFragments = data.get("chunkInitFragments");
  102. if (!chunkInitFragments) {
  103. chunkInitFragments = [];
  104. data.set("chunkInitFragments", chunkInitFragments);
  105. }
  106. }
  107. return chunkInitFragments;
  108. }
  109. };
  110. /**
  111. * @param {Dependency} dependency dependency
  112. */
  113. const handleDependency = (dependency) => {
  114. const constructor =
  115. /** @type {new (...args: EXPECTED_ANY[]) => Dependency} */
  116. (dependency.constructor);
  117. const template = generateContext.dependencyTemplates.get(constructor);
  118. if (!template) {
  119. throw new Error(
  120. `No template for dependency: ${dependency.constructor.name}`
  121. );
  122. }
  123. template.apply(dependency, source, templateContext);
  124. };
  125. for (const dependency of module.dependencies) {
  126. handleDependency(dependency);
  127. }
  128. switch (generateContext.type) {
  129. case "javascript": {
  130. /** @type {BuildInfo} */
  131. (module.buildInfo).cssData = cssData;
  132. generateContext.runtimeRequirements.add(RuntimeGlobals.module);
  133. if (generateContext.concatenationScope) {
  134. const source = new ConcatSource();
  135. const usedIdentifiers = new Set();
  136. const { RESERVED_IDENTIFIER } = getPropertyName();
  137. for (const [name, v] of cssData.exports) {
  138. const usedName = generateContext.moduleGraph
  139. .getExportInfo(module, name)
  140. .getUsedName(name, generateContext.runtime);
  141. if (!usedName) {
  142. continue;
  143. }
  144. let identifier = Template.toIdentifier(usedName);
  145. if (RESERVED_IDENTIFIER.has(identifier)) {
  146. identifier = `_${identifier}`;
  147. }
  148. const i = 0;
  149. while (usedIdentifiers.has(identifier)) {
  150. identifier = Template.toIdentifier(name + i);
  151. }
  152. usedIdentifiers.add(identifier);
  153. generateContext.concatenationScope.registerExport(name, identifier);
  154. source.add(
  155. `${
  156. generateContext.runtimeTemplate.supportsConst()
  157. ? "const"
  158. : "var"
  159. } ${identifier} = ${JSON.stringify(v)};\n`
  160. );
  161. }
  162. return source;
  163. }
  164. if (
  165. cssData.exports.size === 0 &&
  166. !(/** @type {BuildMeta} */ (module.buildMeta).isCSSModule)
  167. ) {
  168. return new RawSource("");
  169. }
  170. const needNsObj =
  171. this.esModule &&
  172. generateContext.moduleGraph
  173. .getExportsInfo(module)
  174. .otherExportsInfo.getUsed(generateContext.runtime) !==
  175. UsageState.Unused;
  176. if (needNsObj) {
  177. generateContext.runtimeRequirements.add(
  178. RuntimeGlobals.makeNamespaceObject
  179. );
  180. }
  181. const exports = [];
  182. for (const [name, v] of cssData.exports) {
  183. exports.push(`\t${JSON.stringify(name)}: ${JSON.stringify(v)}`);
  184. }
  185. return new RawSource(
  186. `${needNsObj ? `${RuntimeGlobals.makeNamespaceObject}(` : ""}${
  187. module.moduleArgument
  188. }.exports = {\n${exports.join(",\n")}\n}${needNsObj ? ")" : ""};`
  189. );
  190. }
  191. case "css": {
  192. if (module.presentationalDependencies !== undefined) {
  193. for (const dependency of module.presentationalDependencies) {
  194. handleDependency(dependency);
  195. }
  196. }
  197. generateContext.runtimeRequirements.add(RuntimeGlobals.hasCssModules);
  198. return InitFragment.addToSource(source, initFragments, generateContext);
  199. }
  200. default:
  201. return null;
  202. }
  203. }
  204. /**
  205. * @param {Error} error the error
  206. * @param {NormalModule} module module for which the code should be generated
  207. * @param {GenerateContext} generateContext context for generate
  208. * @returns {Source | null} generated code
  209. */
  210. generateError(error, module, generateContext) {
  211. switch (generateContext.type) {
  212. case "javascript": {
  213. return new RawSource(
  214. `throw new Error(${JSON.stringify(error.message)});`
  215. );
  216. }
  217. case "css": {
  218. return new RawSource(`/**\n ${error.message} \n**/`);
  219. }
  220. default:
  221. return null;
  222. }
  223. }
  224. /**
  225. * @param {NormalModule} module fresh module
  226. * @returns {SourceTypes} available types (do not mutate)
  227. */
  228. getTypes(module) {
  229. // TODO, find a better way to prevent the original module from being removed after concatenation, maybe it is a bug
  230. if (this.exportsOnly) {
  231. return JS_AND_CSS_EXPORT_TYPES;
  232. }
  233. const sourceTypes = new Set();
  234. const connections = this._moduleGraph.getIncomingConnections(module);
  235. for (const connection of connections) {
  236. if (!connection.originModule) {
  237. continue;
  238. }
  239. if (connection.originModule.type.split("/")[0] !== CSS_TYPE) {
  240. sourceTypes.add(JS_TYPE);
  241. }
  242. }
  243. if (sourceTypes.has(JS_TYPE)) {
  244. return JS_AND_CSS_TYPES;
  245. }
  246. return CSS_TYPES;
  247. }
  248. /**
  249. * @param {NormalModule} module the module
  250. * @param {string=} type source type
  251. * @returns {number} estimate size of the module
  252. */
  253. getSize(module, type) {
  254. switch (type) {
  255. case "javascript": {
  256. const cssData = /** @type {BuildInfo} */ (module.buildInfo).cssData;
  257. if (!cssData) {
  258. return 42;
  259. }
  260. if (cssData.exports.size === 0) {
  261. if (/** @type {BuildMeta} */ (module.buildMeta).isCSSModule) {
  262. return 42;
  263. }
  264. return 0;
  265. }
  266. const exports = cssData.exports;
  267. const stringifiedExports = JSON.stringify(
  268. [...exports].reduce((obj, [key, value]) => {
  269. obj[key] = value;
  270. return obj;
  271. }, /** @type {Record<string, string>} */ ({}))
  272. );
  273. return stringifiedExports.length + 42;
  274. }
  275. case "css": {
  276. const originalSource = module.originalSource();
  277. if (!originalSource) {
  278. return 0;
  279. }
  280. return originalSource.size();
  281. }
  282. default:
  283. return 0;
  284. }
  285. }
  286. /**
  287. * @param {Hash} hash hash that will be modified
  288. * @param {UpdateHashContext} updateHashContext context for updating hash
  289. */
  290. updateHash(hash, { module }) {
  291. hash.update(/** @type {boolean} */ (this.esModule).toString());
  292. }
  293. }
  294. module.exports = CssGenerator;