AssetParser.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. if (typeof this.dataUrlCondition === "function") {
  30. state.module.buildInfo.dataUrl = this.dataUrlCondition(source, {
  31. filename: state.module.matchResource || state.module.resource,
  32. module: state.module
  33. });
  34. } else if (typeof this.dataUrlCondition === "boolean") {
  35. state.module.buildInfo.dataUrl = this.dataUrlCondition;
  36. } else if (
  37. this.dataUrlCondition &&
  38. typeof this.dataUrlCondition === "object"
  39. ) {
  40. state.module.buildInfo.dataUrl =
  41. Buffer.byteLength(source) <= this.dataUrlCondition.maxSize;
  42. } else {
  43. throw new Error("Unexpected dataUrlCondition type");
  44. }
  45. return state;
  46. }
  47. }
  48. module.exports = AssetParser;