2015-02-05 06:21:55 +08:00
|
|
|
/*
|
|
|
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
|
|
|
Author Tobias Koppers @sokra
|
|
|
|
*/
|
2018-07-30 23:08:51 +08:00
|
|
|
|
2017-01-04 04:19:06 +08:00
|
|
|
"use strict";
|
2015-02-05 06:21:55 +08:00
|
|
|
|
2018-02-11 12:27:09 +08:00
|
|
|
const asyncLib = require("neo-async");
|
2017-01-04 04:19:06 +08:00
|
|
|
const NormalModule = require("./NormalModule");
|
2018-07-30 23:08:51 +08:00
|
|
|
const PrefetchDependency = require("./dependencies/PrefetchDependency");
|
2017-01-04 04:19:06 +08:00
|
|
|
|
2018-07-09 20:48:28 +08:00
|
|
|
/** @typedef {import("./Compiler")} Compiler */
|
2018-06-21 18:39:48 +08:00
|
|
|
|
2025-04-23 20:03:37 +08:00
|
|
|
const PLUGIN_NAME = "AutomaticPrefetchPlugin";
|
|
|
|
|
2017-01-04 04:19:06 +08:00
|
|
|
class AutomaticPrefetchPlugin {
|
2018-06-14 22:51:20 +08:00
|
|
|
/**
|
|
|
|
* Apply the plugin
|
2018-11-03 04:05:46 +08:00
|
|
|
* @param {Compiler} compiler the compiler instance
|
2018-06-14 22:51:20 +08:00
|
|
|
* @returns {void}
|
|
|
|
*/
|
2017-01-04 04:19:06 +08:00
|
|
|
apply(compiler) {
|
2018-02-25 09:00:20 +08:00
|
|
|
compiler.hooks.compilation.tap(
|
2025-04-23 20:03:37 +08:00
|
|
|
PLUGIN_NAME,
|
2018-02-25 09:00:20 +08:00
|
|
|
(compilation, { normalModuleFactory }) => {
|
|
|
|
compilation.dependencyFactories.set(
|
|
|
|
PrefetchDependency,
|
|
|
|
normalModuleFactory
|
|
|
|
);
|
|
|
|
}
|
|
|
|
);
|
2024-03-18 01:15:44 +08:00
|
|
|
/** @type {{context: string | null, request: string}[] | null} */
|
2017-01-04 04:19:06 +08:00
|
|
|
let lastModules = null;
|
2025-07-17 00:13:14 +08:00
|
|
|
compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation) => {
|
2020-08-16 22:29:47 +08:00
|
|
|
lastModules = [];
|
|
|
|
|
|
|
|
for (const m of compilation.modules) {
|
|
|
|
if (m instanceof NormalModule) {
|
|
|
|
lastModules.push({
|
|
|
|
context: m.context,
|
|
|
|
request: m.request
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2015-02-05 06:21:55 +08:00
|
|
|
});
|
2025-04-23 20:03:37 +08:00
|
|
|
compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => {
|
|
|
|
if (!lastModules) return callback();
|
|
|
|
asyncLib.each(
|
|
|
|
lastModules,
|
|
|
|
(m, callback) => {
|
|
|
|
compilation.addModuleChain(
|
|
|
|
m.context || compiler.context,
|
|
|
|
new PrefetchDependency(`!!${m.request}`),
|
|
|
|
callback
|
|
|
|
);
|
|
|
|
},
|
2025-07-17 00:13:14 +08:00
|
|
|
(err) => {
|
2025-04-23 20:03:37 +08:00
|
|
|
lastModules = null;
|
|
|
|
callback(err);
|
|
|
|
}
|
|
|
|
);
|
|
|
|
});
|
2017-01-04 04:19:06 +08:00
|
|
|
}
|
|
|
|
}
|
2025-07-02 20:10:54 +08:00
|
|
|
|
2017-01-04 04:19:06 +08:00
|
|
|
module.exports = AutomaticPrefetchPlugin;
|