1 |
|
2 |
|
3 |
|
4 |
|
5 | "use strict";
|
6 |
|
7 | const asyncLib = require("neo-async");
|
8 | const PrefetchDependency = require("./dependencies/PrefetchDependency");
|
9 | const NormalModule = require("./NormalModule");
|
10 |
|
11 |
|
12 |
|
13 | class AutomaticPrefetchPlugin {
|
14 | |
15 |
|
16 |
|
17 |
|
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;
|