UNPKG

1.43 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 asyncLib = require("neo-async");
9const NormalModule = require("./NormalModule");
10const PrefetchDependency = require("./dependencies/PrefetchDependency");
11
12/** @typedef {import("./Compiler")} Compiler */
13
14class AutomaticPrefetchPlugin {
15 /**
16 * Apply the plugin
17 * @param {Compiler} compiler the compiler instance
18 * @returns {void}
19 */
20 apply(compiler) {
21 compiler.hooks.compilation.tap(
22 "AutomaticPrefetchPlugin",
23 (compilation, { normalModuleFactory }) => {
24 compilation.dependencyFactories.set(
25 PrefetchDependency,
26 normalModuleFactory
27 );
28 }
29 );
30 let lastModules = null;
31 compiler.hooks.afterCompile.tap("AutomaticPrefetchPlugin", compilation => {
32 lastModules = Array.from(compilation.modules)
33 .filter(m => m instanceof NormalModule)
34 .map((/** @type {NormalModule} */ m) => ({
35 context: m.context,
36 request: m.request
37 }));
38 });
39 compiler.hooks.make.tapAsync(
40 "AutomaticPrefetchPlugin",
41 (compilation, callback) => {
42 if (!lastModules) return callback();
43 asyncLib.forEach(
44 lastModules,
45 (m, callback) => {
46 compilation.addModuleChain(
47 m.context || compiler.context,
48 new PrefetchDependency(m.request),
49 callback
50 );
51 },
52 callback
53 );
54 }
55 );
56 }
57}
58module.exports = AutomaticPrefetchPlugin;