[6a3a178] | 1 | /*
|
---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
| 3 | Author Tobias Koppers @sokra
|
---|
| 4 | */
|
---|
| 5 |
|
---|
| 6 | "use strict";
|
---|
| 7 |
|
---|
| 8 | const asyncLib = require("neo-async");
|
---|
| 9 | const NormalModule = require("./NormalModule");
|
---|
| 10 | const PrefetchDependency = require("./dependencies/PrefetchDependency");
|
---|
| 11 |
|
---|
| 12 | /** @typedef {import("./Compiler")} Compiler */
|
---|
| 13 |
|
---|
| 14 | class 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 = [];
|
---|
| 33 |
|
---|
| 34 | for (const m of compilation.modules) {
|
---|
| 35 | if (m instanceof NormalModule) {
|
---|
| 36 | lastModules.push({
|
---|
| 37 | context: m.context,
|
---|
| 38 | request: m.request
|
---|
| 39 | });
|
---|
| 40 | }
|
---|
| 41 | }
|
---|
| 42 | });
|
---|
| 43 | compiler.hooks.make.tapAsync(
|
---|
| 44 | "AutomaticPrefetchPlugin",
|
---|
| 45 | (compilation, callback) => {
|
---|
| 46 | if (!lastModules) return callback();
|
---|
| 47 | asyncLib.forEach(
|
---|
| 48 | lastModules,
|
---|
| 49 | (m, callback) => {
|
---|
| 50 | compilation.addModuleChain(
|
---|
| 51 | m.context || compiler.context,
|
---|
| 52 | new PrefetchDependency(`!!${m.request}`),
|
---|
| 53 | callback
|
---|
| 54 | );
|
---|
| 55 | },
|
---|
| 56 | err => {
|
---|
| 57 | lastModules = null;
|
---|
| 58 | callback(err);
|
---|
| 59 | }
|
---|
| 60 | );
|
---|
| 61 | }
|
---|
| 62 | );
|
---|
| 63 | }
|
---|
| 64 | }
|
---|
| 65 | module.exports = AutomaticPrefetchPlugin;
|
---|