1 |
3a515b92
|
cagy
|
/*
|
2 |
|
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
3 |
|
|
Author Tobias Koppers @sokra
|
4 |
|
|
*/
|
5 |
|
|
"use strict";
|
6 |
|
|
|
7 |
|
|
const asyncLib = require("neo-async");
|
8 |
|
|
const PrefetchDependency = require("./dependencies/PrefetchDependency");
|
9 |
|
|
const NormalModule = require("./NormalModule");
|
10 |
|
|
|
11 |
|
|
/** @typedef {import("./Compiler")} Compiler */
|
12 |
|
|
|
13 |
|
|
class AutomaticPrefetchPlugin {
|
14 |
|
|
/**
|
15 |
|
|
* Apply the plugin
|
16 |
|
|
* @param {Compiler} compiler Webpack Compiler
|
17 |
|
|
* @returns {void}
|
18 |
|
|
*/
|
19 |
|
|
apply(compiler) {
|
20 |
|
|
compiler.hooks.compilation.tap(
|
21 |
|
|
"AutomaticPrefetchPlugin",
|
22 |
|
|
(compilation, { normalModuleFactory }) => {
|
23 |
|
|
compilation.dependencyFactories.set(
|
24 |
|
|
PrefetchDependency,
|
25 |
|
|
normalModuleFactory
|
26 |
|
|
);
|
27 |
|
|
}
|
28 |
|
|
);
|
29 |
|
|
let lastModules = null;
|
30 |
|
|
compiler.hooks.afterCompile.tap("AutomaticPrefetchPlugin", compilation => {
|
31 |
|
|
lastModules = compilation.modules
|
32 |
|
|
.filter(m => m instanceof NormalModule)
|
33 |
|
|
.map((/** @type {NormalModule} */ m) => ({
|
34 |
|
|
context: m.context,
|
35 |
|
|
request: m.request
|
36 |
|
|
}));
|
37 |
|
|
});
|
38 |
|
|
compiler.hooks.make.tapAsync(
|
39 |
|
|
"AutomaticPrefetchPlugin",
|
40 |
|
|
(compilation, callback) => {
|
41 |
|
|
if (!lastModules) return callback();
|
42 |
|
|
asyncLib.forEach(
|
43 |
|
|
lastModules,
|
44 |
|
|
(m, callback) => {
|
45 |
|
|
compilation.prefetch(
|
46 |
|
|
m.context || compiler.context,
|
47 |
|
|
new PrefetchDependency(m.request),
|
48 |
|
|
callback
|
49 |
|
|
);
|
50 |
|
|
},
|
51 |
|
|
callback
|
52 |
|
|
);
|
53 |
|
|
}
|
54 |
|
|
);
|
55 |
|
|
}
|
56 |
|
|
}
|
57 |
|
|
module.exports = AutomaticPrefetchPlugin;
|