JsonExportsDependency.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const makeSerializable = require("../util/makeSerializable");
  7. const NullDependency = require("./NullDependency");
  8. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  9. /** @typedef {import("../Dependency").ExportSpec} ExportSpec */
  10. /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
  11. /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
  12. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  13. /** @typedef {import("../json/JsonData")} JsonData */
  14. /** @typedef {import("../util/Hash")} Hash */
  15. const getExportsFromData = data => {
  16. if (data && typeof data === "object") {
  17. if (Array.isArray(data)) {
  18. return data.length < 100
  19. ? data.map((item, idx) => {
  20. return {
  21. name: `${idx}`,
  22. canMangle: true,
  23. exports: getExportsFromData(item)
  24. };
  25. })
  26. : undefined;
  27. } else {
  28. const exports = [];
  29. for (const key of Object.keys(data)) {
  30. exports.push({
  31. name: key,
  32. canMangle: true,
  33. exports: getExportsFromData(data[key])
  34. });
  35. }
  36. return exports;
  37. }
  38. }
  39. return undefined;
  40. };
  41. class JsonExportsDependency extends NullDependency {
  42. /**
  43. * @param {JsonData=} data json data
  44. */
  45. constructor(data) {
  46. super();
  47. this.data = data;
  48. }
  49. get type() {
  50. return "json exports";
  51. }
  52. /**
  53. * Returns the exported names
  54. * @param {ModuleGraph} moduleGraph module graph
  55. * @returns {ExportsSpec | undefined} export names
  56. */
  57. getExports(moduleGraph) {
  58. return {
  59. exports: getExportsFromData(this.data && this.data.get()),
  60. dependencies: undefined
  61. };
  62. }
  63. /**
  64. * Update the hash
  65. * @param {Hash} hash hash to be updated
  66. * @param {UpdateHashContext} context context
  67. * @returns {void}
  68. */
  69. updateHash(hash, context) {
  70. this.data.updateHash(hash);
  71. }
  72. serialize(context) {
  73. const { write } = context;
  74. write(this.data);
  75. super.serialize(context);
  76. }
  77. deserialize(context) {
  78. const { read } = context;
  79. this.data = read();
  80. super.deserialize(context);
  81. }
  82. }
  83. makeSerializable(
  84. JsonExportsDependency,
  85. "webpack/lib/dependencies/JsonExportsDependency"
  86. );
  87. module.exports = JsonExportsDependency;