webpack/lib/cache/MemoryCachePlugin.js

60 lines
1.5 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
2019-05-13 17:03:10 +08:00
const Cache = require("../Cache");
/** @typedef {import("webpack-sources").Source} Source */
2025-04-16 22:04:11 +08:00
/** @typedef {import("../Cache").Data} Data */
/** @typedef {import("../Cache").Etag} Etag */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */
class MemoryCachePlugin {
/**
2020-04-23 16:48:36 +08:00
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
2025-04-16 22:04:11 +08:00
/** @type {Map<string, { etag: Etag | null, data: Data } | null>} */
const cache = new Map();
compiler.cache.hooks.store.tap(
2019-05-13 17:03:10 +08:00
{ name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY },
(identifier, etag, data) => {
cache.set(identifier, { etag, data });
}
);
compiler.cache.hooks.get.tap(
2019-05-13 17:03:10 +08:00
{ name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY },
(identifier, etag, gotHandlers) => {
const cacheEntry = cache.get(identifier);
if (cacheEntry === null) {
return null;
} else if (cacheEntry !== undefined) {
return cacheEntry.etag === etag ? cacheEntry.data : null;
}
gotHandlers.push((result, callback) => {
if (result === undefined) {
cache.set(identifier, null);
} else {
cache.set(identifier, { etag, data: result });
}
return callback();
});
}
);
compiler.cache.hooks.shutdown.tap(
{ name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY },
() => {
cache.clear();
}
);
}
}
module.exports = MemoryCachePlugin;