UNPKG

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