CssUrlDependency.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. const RawDataUrlModule = require("../asset/RawDataUrlModule");
  7. const makeSerializable = require("../util/makeSerializable");
  8. const memoize = require("../util/memoize");
  9. const ModuleDependency = require("./ModuleDependency");
  10. /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
  11. /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
  12. /** @typedef {import("../Dependency")} Dependency */
  13. /** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */
  14. /** @typedef {import("../Module")} Module */
  15. /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
  16. /** @typedef {import("../Module").CodeGenerationResultData} CodeGenerationResultData */
  17. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  18. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  19. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  20. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  21. const getIgnoredRawDataUrlModule = memoize(
  22. () => new RawDataUrlModule("data:,", "ignored-asset", "(ignored asset)")
  23. );
  24. class CssUrlDependency extends ModuleDependency {
  25. /**
  26. * @param {string} request request
  27. * @param {Range} range range of the argument
  28. * @param {"string" | "url" | "src"} urlType dependency type e.g. url() or string
  29. */
  30. constructor(request, range, urlType) {
  31. super(request);
  32. this.range = range;
  33. this.urlType = urlType;
  34. }
  35. get type() {
  36. return "css url()";
  37. }
  38. get category() {
  39. return "url";
  40. }
  41. /**
  42. * @param {string} context context directory
  43. * @returns {Module} ignored module
  44. */
  45. createIgnoredModule(context) {
  46. return getIgnoredRawDataUrlModule();
  47. }
  48. /**
  49. * @param {ObjectSerializerContext} context context
  50. */
  51. serialize(context) {
  52. const { write } = context;
  53. write(this.urlType);
  54. super.serialize(context);
  55. }
  56. /**
  57. * @param {ObjectDeserializerContext} context context
  58. */
  59. deserialize(context) {
  60. const { read } = context;
  61. this.urlType = read();
  62. super.deserialize(context);
  63. }
  64. }
  65. /**
  66. * @param {string} str string
  67. * @returns {string} string in quotes if needed
  68. */
  69. const cssEscapeString = (str) => {
  70. let countWhiteOrBracket = 0;
  71. let countQuotation = 0;
  72. let countApostrophe = 0;
  73. for (let i = 0; i < str.length; i++) {
  74. const cc = str.charCodeAt(i);
  75. switch (cc) {
  76. case 9: // tab
  77. case 10: // nl
  78. case 32: // space
  79. case 40: // (
  80. case 41: // )
  81. countWhiteOrBracket++;
  82. break;
  83. case 34:
  84. countQuotation++;
  85. break;
  86. case 39:
  87. countApostrophe++;
  88. break;
  89. }
  90. }
  91. if (countWhiteOrBracket < 2) {
  92. return str.replace(/[\n\t ()'"\\]/g, (m) => `\\${m}`);
  93. } else if (countQuotation <= countApostrophe) {
  94. return `"${str.replace(/[\n"\\]/g, (m) => `\\${m}`)}"`;
  95. }
  96. return `'${str.replace(/[\n'\\]/g, (m) => `\\${m}`)}'`;
  97. };
  98. CssUrlDependency.Template = class CssUrlDependencyTemplate extends (
  99. ModuleDependency.Template
  100. ) {
  101. /**
  102. * @param {Dependency} dependency the dependency for which the template should be applied
  103. * @param {ReplaceSource} source the current replace source which can be modified
  104. * @param {DependencyTemplateContext} templateContext the context object
  105. * @returns {void}
  106. */
  107. apply(
  108. dependency,
  109. source,
  110. { type, moduleGraph, runtimeTemplate, codeGenerationResults }
  111. ) {
  112. if (type === "javascript") return;
  113. const dep = /** @type {CssUrlDependency} */ (dependency);
  114. const module = /** @type {Module} */ (moduleGraph.getModule(dep));
  115. /** @type {string | undefined} */
  116. let newValue;
  117. switch (dep.urlType) {
  118. case "string":
  119. newValue = cssEscapeString(
  120. this.assetUrl({
  121. module,
  122. codeGenerationResults
  123. })
  124. );
  125. break;
  126. case "url":
  127. newValue = `url(${cssEscapeString(
  128. this.assetUrl({
  129. module,
  130. codeGenerationResults
  131. })
  132. )})`;
  133. break;
  134. case "src":
  135. newValue = `src(${cssEscapeString(
  136. this.assetUrl({
  137. module,
  138. codeGenerationResults
  139. })
  140. )})`;
  141. break;
  142. }
  143. source.replace(
  144. dep.range[0],
  145. dep.range[1] - 1,
  146. /** @type {string} */ (newValue)
  147. );
  148. }
  149. /**
  150. * @param {object} options options object
  151. * @param {Module} options.module the module
  152. * @param {RuntimeSpec=} options.runtime runtime
  153. * @param {CodeGenerationResults} options.codeGenerationResults the code generation results
  154. * @returns {string} the url of the asset
  155. */
  156. assetUrl({ runtime, module, codeGenerationResults }) {
  157. if (!module) {
  158. return "data:,";
  159. }
  160. const codeGen = codeGenerationResults.get(module, runtime);
  161. const data = codeGen.data;
  162. if (!data) return "data:,";
  163. const url = data.get("url");
  164. if (!url || !url["css-url"]) return "data:,";
  165. return url["css-url"];
  166. }
  167. };
  168. makeSerializable(CssUrlDependency, "webpack/lib/dependencies/CssUrlDependency");
  169. CssUrlDependency.PUBLIC_PATH_AUTO = "__WEBPACK_CSS_PUBLIC_PATH_AUTO__";
  170. module.exports = CssUrlDependency;