CssUrlDependency.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. const makeSerializable = require("../util/makeSerializable");
  7. const memoize = require("../util/memoize");
  8. const ModuleDependency = require("./ModuleDependency");
  9. /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
  10. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  11. /** @typedef {import("../Dependency")} Dependency */
  12. /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
  13. /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
  14. /** @typedef {import("../Module")} Module */
  15. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  16. /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
  17. /** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */
  18. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  19. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  20. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  21. /** @typedef {import("../util/Hash")} Hash */
  22. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  23. const getRawDataUrlModule = memoize(() => require("../asset/RawDataUrlModule"));
  24. class CssUrlDependency extends ModuleDependency {
  25. /**
  26. * @param {string} request request
  27. * @param {Range} range range of the argument
  28. * @param {"string" | "url"} 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 | null} a module
  44. */
  45. createIgnoredModule(context) {
  46. const RawDataUrlModule = getRawDataUrlModule();
  47. return new RawDataUrlModule("data:,", `ignored-asset`, `(ignored asset)`);
  48. }
  49. /**
  50. * @param {ObjectSerializerContext} context context
  51. */
  52. serialize(context) {
  53. const { write } = context;
  54. write(this.urlType);
  55. super.serialize(context);
  56. }
  57. /**
  58. * @param {ObjectDeserializerContext} context context
  59. */
  60. deserialize(context) {
  61. const { read } = context;
  62. this.urlType = read();
  63. super.deserialize(context);
  64. }
  65. }
  66. /**
  67. * @param {string} str string
  68. * @returns {string} string in quotes if needed
  69. */
  70. const cssEscapeString = str => {
  71. let countWhiteOrBracket = 0;
  72. let countQuotation = 0;
  73. let countApostrophe = 0;
  74. for (let i = 0; i < str.length; i++) {
  75. const cc = str.charCodeAt(i);
  76. switch (cc) {
  77. case 9: // tab
  78. case 10: // nl
  79. case 32: // space
  80. case 40: // (
  81. case 41: // )
  82. countWhiteOrBracket++;
  83. break;
  84. case 34:
  85. countQuotation++;
  86. break;
  87. case 39:
  88. countApostrophe++;
  89. break;
  90. }
  91. }
  92. if (countWhiteOrBracket < 2) {
  93. return str.replace(/[\n\t ()'"\\]/g, m => `\\${m}`);
  94. } else if (countQuotation <= countApostrophe) {
  95. return `"${str.replace(/[\n"\\]/g, m => `\\${m}`)}"`;
  96. } else {
  97. return `'${str.replace(/[\n'\\]/g, m => `\\${m}`)}'`;
  98. }
  99. };
  100. CssUrlDependency.Template = class CssUrlDependencyTemplate extends (
  101. ModuleDependency.Template
  102. ) {
  103. /**
  104. * @param {Dependency} dependency the dependency for which the template should be applied
  105. * @param {ReplaceSource} source the current replace source which can be modified
  106. * @param {DependencyTemplateContext} templateContext the context object
  107. * @returns {void}
  108. */
  109. apply(
  110. dependency,
  111. source,
  112. { moduleGraph, runtimeTemplate, codeGenerationResults }
  113. ) {
  114. const dep = /** @type {CssUrlDependency} */ (dependency);
  115. /** @type {string | undefined} */
  116. let newValue;
  117. switch (dep.urlType) {
  118. case "string":
  119. newValue = cssEscapeString(
  120. runtimeTemplate.assetUrl({
  121. publicPath: "",
  122. module: /** @type {Module} */ (moduleGraph.getModule(dep)),
  123. codeGenerationResults
  124. })
  125. );
  126. break;
  127. case "url":
  128. newValue = `url(${cssEscapeString(
  129. runtimeTemplate.assetUrl({
  130. publicPath: "",
  131. module: /** @type {Module} */ (moduleGraph.getModule(dep)),
  132. codeGenerationResults
  133. })
  134. )})`;
  135. break;
  136. }
  137. source.replace(
  138. dep.range[0],
  139. dep.range[1] - 1,
  140. /** @type {string} */ (newValue)
  141. );
  142. }
  143. };
  144. makeSerializable(CssUrlDependency, "webpack/lib/dependencies/CssUrlDependency");
  145. module.exports = CssUrlDependency;