| 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 | const PLUGIN_NAME = "AutomaticPrefetchPlugin";
|
|---|
| 15 |
|
|---|
| 16 | /**
|
|---|
| 17 | * Records modules from one compilation and adds them back as prefetch
|
|---|
| 18 | * dependencies in the next compilation.
|
|---|
| 19 | */
|
|---|
| 20 | class AutomaticPrefetchPlugin {
|
|---|
| 21 | /**
|
|---|
| 22 | * Registers hooks that remember previously built normal modules and enqueue
|
|---|
| 23 | * them as `PrefetchDependency` requests during the next make phase.
|
|---|
| 24 | * @param {Compiler} compiler the compiler instance
|
|---|
| 25 | * @returns {void}
|
|---|
| 26 | */
|
|---|
| 27 | apply(compiler) {
|
|---|
| 28 | compiler.hooks.compilation.tap(
|
|---|
| 29 | PLUGIN_NAME,
|
|---|
| 30 | (compilation, { normalModuleFactory }) => {
|
|---|
| 31 | compilation.dependencyFactories.set(
|
|---|
| 32 | PrefetchDependency,
|
|---|
| 33 | normalModuleFactory
|
|---|
| 34 | );
|
|---|
| 35 | }
|
|---|
| 36 | );
|
|---|
| 37 | /** @type {{ context: string | null, request: string }[] | null} */
|
|---|
| 38 | let lastModules = null;
|
|---|
| 39 | compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation) => {
|
|---|
| 40 | lastModules = [];
|
|---|
| 41 |
|
|---|
| 42 | for (const m of compilation.modules) {
|
|---|
| 43 | if (m instanceof NormalModule) {
|
|---|
| 44 | lastModules.push({
|
|---|
| 45 | context: m.context,
|
|---|
| 46 | request: m.request
|
|---|
| 47 | });
|
|---|
| 48 | }
|
|---|
| 49 | }
|
|---|
| 50 | });
|
|---|
| 51 | compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => {
|
|---|
| 52 | if (!lastModules) return callback();
|
|---|
| 53 | asyncLib.each(
|
|---|
| 54 | lastModules,
|
|---|
| 55 | (m, callback) => {
|
|---|
| 56 | compilation.addModuleChain(
|
|---|
| 57 | m.context || compiler.context,
|
|---|
| 58 | new PrefetchDependency(`!!${m.request}`),
|
|---|
| 59 | callback
|
|---|
| 60 | );
|
|---|
| 61 | },
|
|---|
| 62 | (err) => {
|
|---|
| 63 | lastModules = null;
|
|---|
| 64 | callback(err);
|
|---|
| 65 | }
|
|---|
| 66 | );
|
|---|
| 67 | });
|
|---|
| 68 | }
|
|---|
| 69 | }
|
|---|
| 70 |
|
|---|
| 71 | module.exports = AutomaticPrefetchPlugin;
|
|---|