DataUriPlugin.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const NormalModule = require("../NormalModule");
  7. const { URIRegEx, decodeDataURI } = require("../util/dataURL");
  8. /** @import Compiler from "../Compiler" */
  9. const PLUGIN_NAME = "DataUriPlugin";
  10. class DataUriPlugin {
  11. /**
  12. * Applies the plugin by registering its hooks on the compiler.
  13. * @param {Compiler} compiler the compiler instance
  14. * @returns {void}
  15. */
  16. apply(compiler) {
  17. compiler.hooks.compilation.tap(
  18. PLUGIN_NAME,
  19. (compilation, { normalModuleFactory }) => {
  20. normalModuleFactory.hooks.resolveForScheme
  21. .for("data")
  22. .tap(PLUGIN_NAME, (resourceData, resolveData) => {
  23. const match = URIRegEx.exec(resourceData.resource);
  24. if (match) {
  25. resourceData.data.mimetype = match[1] || "";
  26. resourceData.data.parameters = match[2] || "";
  27. resourceData.data.encoding = /** @type {"base64" | false} */ (
  28. match[3] || false
  29. );
  30. resourceData.data.encodedContent = match[4] || "";
  31. }
  32. // Inherit the issuer's resolution context so any nested
  33. // dependencies discovered while parsing the data URI's body
  34. // (e.g. `url(...)` / `@import` inside an inline CSS data
  35. // URI) resolve relative to where the URI was referenced
  36. // from, instead of against the synthetic `data:.../` path
  37. // that `getContext("data:…")` would otherwise infer.
  38. if (
  39. resourceData.context === undefined &&
  40. resolveData.context !== undefined
  41. ) {
  42. resourceData.context = resolveData.context;
  43. }
  44. });
  45. NormalModule.getCompilationHooks(compilation)
  46. .readResourceForScheme.for("data")
  47. .tap(PLUGIN_NAME, (resource) => decodeDataURI(resource));
  48. }
  49. );
  50. }
  51. }
  52. module.exports = DataUriPlugin;