HtmlInlineStyleDependency.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const { CSS_TEXT_TYPE } = require("../ModuleSourceTypeConstants");
  6. const makeSerializable = require("../util/makeSerializable");
  7. const ModuleDependency = require("./ModuleDependency");
  8. /** @import { ReplaceSource } from "webpack-sources" */
  9. /** @import CodeGenerationResults from "../CodeGenerationResults" */
  10. /** @import Dependency, { UpdateHashContext } from "../Dependency" */
  11. /** @import { DependencyTemplateContext } from "../DependencyTemplate" */
  12. /** @import Module from "../Module" */
  13. /** @import { Range } from "../javascript/JavascriptParser" */
  14. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext<boolean[]>} ObjectDeserializerContext */
  15. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext<boolean[]>} ObjectSerializerContext */
  16. /** @import Hash from "../util/Hash" */
  17. const TRAILING_WHITESPACE_REGEXP = /\s+$/;
  18. // One pass over the source: each char is replaced once and replacements aren't
  19. // re-scanned, so this matches the `&`-first sequential escape chain exactly
  20. // while avoiding two extra full-string scans + intermediate strings.
  21. const ATTR_ESCAPE_REGEXP = /[&"']/g;
  22. /** @type {Record<string, string>} */
  23. const ATTR_ESCAPES = { "&": "&amp;", '"': "&quot;", "'": "&#39;" };
  24. /**
  25. * @param {string} c matched character
  26. * @returns {string} the HTML-attribute-escaped entity
  27. */
  28. const escapeAttrChar = (c) => ATTR_ESCAPES[c];
  29. /**
  30. * Represents inline CSS in an HTML module — either a `<style>...</style>`
  31. * block (a stylesheet) or an element's `style="..."` attribute (a CSS
  32. * block's contents). The content is fed into webpack's CSS pipeline as a
  33. * virtual CSS module with `exportType: "text"` so `url()` and `\@import`
  34. * references are resolved relative to the HTML file. At render time the
  35. * original content range is replaced with the processed CSS text read from
  36. * the CSS module's code generation data.
  37. */
  38. class HtmlInlineStyleDependency extends ModuleDependency {
  39. /**
  40. * Creates an instance of HtmlInlineStyleDependency.
  41. * @param {string} request virtual request resolving to the inline CSS (data URI)
  42. * @param {Range} range range of the inline CSS content (between `<style>` and `</style>`, or the `style` attribute value)
  43. * @param {boolean=} attribute true when the source is a `style="..."` attribute (a block's contents) rather than a `<style>` block (stylesheet)
  44. * @param {boolean=} inAttribute true when the range is an attribute value (decoded on parse, so the processed CSS must be re-escaped on write-back); defaults to `attribute` — differs only for attribute values parsed as full stylesheets
  45. */
  46. constructor(request, range, attribute = false, inAttribute = attribute) {
  47. super(request);
  48. this.range = range;
  49. /** @type {boolean} */
  50. this.attribute = attribute;
  51. /** @type {boolean} */
  52. this.inAttribute = inAttribute;
  53. }
  54. get type() {
  55. return "html inline style";
  56. }
  57. get category() {
  58. return this.attribute ? "html-style-attribute" : "html-style";
  59. }
  60. /**
  61. * Updates the hash with the data contributed by this instance.
  62. * @param {Hash} hash hash to be updated
  63. * @param {UpdateHashContext} context context
  64. * @returns {void}
  65. */
  66. updateHash(hash, context) {
  67. // Recurse so the inline CSS's transitive deps (e.g. `url(asset)`) propagate up.
  68. const { chunkGraph } = context;
  69. const module = chunkGraph.moduleGraph.getModule(this);
  70. if (!module) return;
  71. module.updateHash(hash, context);
  72. }
  73. /**
  74. * Serializes this instance into the provided serializer context.
  75. * @param {ObjectSerializerContext} context context
  76. */
  77. serialize(context) {
  78. super.serialize(context);
  79. context.write(this.attribute);
  80. context.write(this.inAttribute);
  81. }
  82. /**
  83. * Restores this instance from the provided deserializer context.
  84. * @param {ObjectDeserializerContext} context context
  85. */
  86. deserialize(context) {
  87. super.deserialize(context);
  88. this.attribute = context.read();
  89. this.inAttribute = context.read();
  90. }
  91. }
  92. HtmlInlineStyleDependency.Template = class HtmlInlineStyleDependencyTemplate extends (
  93. ModuleDependency.Template
  94. ) {
  95. /**
  96. * Applies the plugin by registering its hooks on the compiler.
  97. * @param {Dependency} dependency the dependency for which the template should be applied
  98. * @param {ReplaceSource} source the current replace source which can be modified
  99. * @param {DependencyTemplateContext} templateContext the context object
  100. * @returns {void}
  101. */
  102. apply(dependency, source, { moduleGraph, runtime, codeGenerationResults }) {
  103. const dep = /** @type {HtmlInlineStyleDependency} */ (dependency);
  104. const module = /** @type {Module} */ (moduleGraph.getModule(dep));
  105. /** @type {string} */
  106. let cssText = "";
  107. if (module) {
  108. const codeGen =
  109. /** @type {CodeGenerationResults} */
  110. (codeGenerationResults).get(module, runtime);
  111. const cssTextSource = codeGen.sources.get(CSS_TEXT_TYPE);
  112. if (cssTextSource) {
  113. cssText = /** @type {string} */ (cssTextSource.source());
  114. }
  115. }
  116. // An attribute value was entity-decoded before parsing, so re-escape
  117. // the processed CSS to keep the surrounding markup valid in any
  118. // quoting context, and drop the trailing newline the CSS generator
  119. // appends so the rewritten attribute stays on one line.
  120. if (dep.inAttribute) {
  121. cssText = cssText
  122. .replace(TRAILING_WHITESPACE_REGEXP, "")
  123. .replace(ATTR_ESCAPE_REGEXP, escapeAttrChar);
  124. }
  125. source.replace(dep.range[0], dep.range[1] - 1, cssText);
  126. }
  127. };
  128. makeSerializable(
  129. HtmlInlineStyleDependency,
  130. "webpack/lib/dependencies/HtmlInlineStyleDependency"
  131. );
  132. module.exports = HtmlInlineStyleDependency;