MemoryCachePlugin.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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").Data} Data */
  9. /** @typedef {import("../Cache").Etag} Etag */
  10. /** @typedef {import("../Compiler")} Compiler */
  11. /** @typedef {import("../Module")} Module */
  12. class MemoryCachePlugin {
  13. /**
  14. * Apply the plugin
  15. * @param {Compiler} compiler the compiler instance
  16. * @returns {void}
  17. */
  18. apply(compiler) {
  19. /** @type {Map<string, { etag: Etag | null, data: Data } | null>} */
  20. const cache = new Map();
  21. compiler.cache.hooks.store.tap(
  22. { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY },
  23. (identifier, etag, data) => {
  24. cache.set(identifier, { etag, data });
  25. }
  26. );
  27. compiler.cache.hooks.get.tap(
  28. { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY },
  29. (identifier, etag, gotHandlers) => {
  30. const cacheEntry = cache.get(identifier);
  31. if (cacheEntry === null) {
  32. return null;
  33. } else if (cacheEntry !== undefined) {
  34. return cacheEntry.etag === etag ? cacheEntry.data : null;
  35. }
  36. gotHandlers.push((result, callback) => {
  37. if (result === undefined) {
  38. cache.set(identifier, null);
  39. } else {
  40. cache.set(identifier, { etag, data: result });
  41. }
  42. return callback();
  43. });
  44. }
  45. );
  46. compiler.cache.hooks.shutdown.tap(
  47. { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY },
  48. () => {
  49. cache.clear();
  50. }
  51. );
  52. }
  53. }
  54. module.exports = MemoryCachePlugin;