MemoryCachePlugin.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Cache = require("../Cache");
  7. /** @typedef {import("webpack-sources").Source} Source */
  8. /** @typedef {import("../Cache").Etag} Etag */
  9. /** @typedef {import("../Compiler")} Compiler */
  10. /** @typedef {import("../Module")} Module */
  11. class MemoryCachePlugin {
  12. /**
  13. * Apply the plugin
  14. * @param {Compiler} compiler the compiler instance
  15. * @returns {void}
  16. */
  17. apply(compiler) {
  18. /** @type {Map<string, { etag: Etag | null, data: any }>} */
  19. const cache = new Map();
  20. compiler.cache.hooks.store.tap(
  21. { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY },
  22. (identifier, etag, data) => {
  23. cache.set(identifier, { etag, data });
  24. }
  25. );
  26. compiler.cache.hooks.get.tap(
  27. { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY },
  28. (identifier, etag, gotHandlers) => {
  29. const cacheEntry = cache.get(identifier);
  30. if (cacheEntry === null) {
  31. return null;
  32. } else if (cacheEntry !== undefined) {
  33. return cacheEntry.etag === etag ? cacheEntry.data : null;
  34. }
  35. gotHandlers.push((result, callback) => {
  36. if (result === undefined) {
  37. cache.set(identifier, null);
  38. } else {
  39. cache.set(identifier, { etag, data: result });
  40. }
  41. return callback();
  42. });
  43. }
  44. );
  45. compiler.cache.hooks.shutdown.tap(
  46. { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY },
  47. () => {
  48. cache.clear();
  49. }
  50. );
  51. }
  52. }
  53. module.exports = MemoryCachePlugin;