AssetSourceGenerator.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Sergey Melyukov @smelukov
  4. */
  5. "use strict";
  6. const { RawSource } = require("webpack-sources");
  7. const Generator = require("../Generator");
  8. const RuntimeGlobals = require("../RuntimeGlobals");
  9. /** @typedef {import("webpack-sources").Source} Source */
  10. /** @typedef {import("../Generator").GenerateContext} GenerateContext */
  11. /** @typedef {import("../NormalModule")} NormalModule */
  12. const TYPES = new Set(["javascript"]);
  13. class AssetSourceGenerator extends Generator {
  14. /**
  15. * @param {NormalModule} module module for which the code should be generated
  16. * @param {GenerateContext} generateContext context for generate
  17. * @returns {Source} generated code
  18. */
  19. generate(module, { chunkGraph, runtimeTemplate, runtimeRequirements }) {
  20. runtimeRequirements.add(RuntimeGlobals.module);
  21. const originalSource = module.originalSource();
  22. if (!originalSource) {
  23. return new RawSource("");
  24. }
  25. const content = originalSource.source();
  26. let encodedSource;
  27. if (typeof content === "string") {
  28. encodedSource = content;
  29. } else {
  30. encodedSource = content.toString("utf-8");
  31. }
  32. return new RawSource(
  33. `${RuntimeGlobals.module}.exports = ${JSON.stringify(encodedSource)};`
  34. );
  35. }
  36. /**
  37. * @param {NormalModule} module fresh module
  38. * @returns {Set<string>} available types (do not mutate)
  39. */
  40. getTypes(module) {
  41. return TYPES;
  42. }
  43. /**
  44. * @param {NormalModule} module the module
  45. * @param {string=} type source type
  46. * @returns {number} estimate size of the module
  47. */
  48. getSize(module, type) {
  49. const originalSource = module.originalSource();
  50. if (!originalSource) {
  51. return 0;
  52. }
  53. // Example: m.exports="abcd"
  54. return originalSource.size() + 12;
  55. }
  56. }
  57. module.exports = AssetSourceGenerator;