CssGenerator.js 9.7 KB

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