AssetParser.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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").AssetParserOptions} AssetParserOptions */
  8. /** @typedef {import("../Parser").ParserState} ParserState */
  9. /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
  10. class AssetParser extends Parser {
  11. /**
  12. * @param {AssetParserOptions["dataUrlCondition"] | boolean} dataUrlCondition condition for inlining as DataUrl
  13. */
  14. constructor(dataUrlCondition) {
  15. super();
  16. this.dataUrlCondition = dataUrlCondition;
  17. }
  18. /**
  19. * @param {string | Buffer | PreparsedAst} source the source to parse
  20. * @param {ParserState} state the parser state
  21. * @returns {ParserState} the parser state
  22. */
  23. parse(source, state) {
  24. if (typeof source === "object" && !Buffer.isBuffer(source)) {
  25. throw new Error("AssetParser doesn't accept preparsed AST");
  26. }
  27. state.module.buildInfo.strict = true;
  28. state.module.buildMeta.exportsType = "default";
  29. state.module.buildMeta.defaultObject = false;
  30. if (typeof this.dataUrlCondition === "function") {
  31. state.module.buildInfo.dataUrl = this.dataUrlCondition(source, {
  32. filename: state.module.matchResource || state.module.resource,
  33. module: state.module
  34. });
  35. } else if (typeof this.dataUrlCondition === "boolean") {
  36. state.module.buildInfo.dataUrl = this.dataUrlCondition;
  37. } else if (
  38. this.dataUrlCondition &&
  39. typeof this.dataUrlCondition === "object"
  40. ) {
  41. state.module.buildInfo.dataUrl =
  42. Buffer.byteLength(source) <= this.dataUrlCondition.maxSize;
  43. } else {
  44. throw new Error("Unexpected dataUrlCondition type");
  45. }
  46. return state;
  47. }
  48. }
  49. module.exports = AssetParser;