AssetParser.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Yuta Hiroto @hiroppy
  4. */
  5. "use strict";
  6. const Parser = require("../Parser");
  7. /** @typedef {import("../../declarations/WebpackOptions").AssetParserDataUrlOptions} AssetParserDataUrlOptions */
  8. /** @typedef {import("../../declarations/WebpackOptions").AssetParserOptions} AssetParserOptions */
  9. /** @typedef {import("../Module").BuildInfo} BuildInfo */
  10. /** @typedef {import("../Module").BuildMeta} BuildMeta */
  11. /** @typedef {import("../Parser").ParserState} ParserState */
  12. /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
  13. class AssetParser extends Parser {
  14. /**
  15. * @param {AssetParserOptions["dataUrlCondition"] | boolean} dataUrlCondition condition for inlining as DataUrl
  16. */
  17. constructor(dataUrlCondition) {
  18. super();
  19. this.dataUrlCondition = dataUrlCondition;
  20. }
  21. /**
  22. * @param {string | Buffer | PreparsedAst} source the source to parse
  23. * @param {ParserState} state the parser state
  24. * @returns {ParserState} the parser state
  25. */
  26. parse(source, state) {
  27. if (typeof source === "object" && !Buffer.isBuffer(source)) {
  28. throw new Error("AssetParser doesn't accept preparsed AST");
  29. }
  30. const buildInfo = /** @type {BuildInfo} */ (state.module.buildInfo);
  31. buildInfo.strict = true;
  32. const buildMeta = /** @type {BuildMeta} */ (state.module.buildMeta);
  33. buildMeta.exportsType = "default";
  34. buildMeta.defaultObject = false;
  35. if (typeof this.dataUrlCondition === "function") {
  36. buildInfo.dataUrl = this.dataUrlCondition(source, {
  37. filename: state.module.matchResource || state.module.resource,
  38. module: state.module
  39. });
  40. } else if (typeof this.dataUrlCondition === "boolean") {
  41. buildInfo.dataUrl = this.dataUrlCondition;
  42. } else if (
  43. this.dataUrlCondition &&
  44. typeof this.dataUrlCondition === "object"
  45. ) {
  46. buildInfo.dataUrl =
  47. Buffer.byteLength(source) <=
  48. /** @type {NonNullable<AssetParserDataUrlOptions["maxSize"]>} */
  49. (this.dataUrlCondition.maxSize);
  50. } else {
  51. throw new Error("Unexpected dataUrlCondition type");
  52. }
  53. return state;
  54. }
  55. }
  56. module.exports = AssetParser;