webpack/lib/AutomaticPrefetchPlugin.js

68 lines
1.6 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
2018-07-30 23:08:51 +08:00
"use strict";
2018-02-11 12:27:09 +08:00
const asyncLib = require("neo-async");
const NormalModule = require("./NormalModule");
2018-07-30 23:08:51 +08:00
const PrefetchDependency = require("./dependencies/PrefetchDependency");
2018-07-09 20:48:28 +08:00
/** @typedef {import("./Compiler")} Compiler */
2018-06-21 18:39:48 +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}
*/
apply(compiler) {
2018-02-25 09:00:20 +08:00
compiler.hooks.compilation.tap(
"AutomaticPrefetchPlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(
PrefetchDependency,
normalModuleFactory
);
}
);
2024-03-18 01:15:44 +08:00
/** @type {{context: string | null, request: string}[] | null} */
let lastModules = null;
2018-02-25 09:00:20 +08:00
compiler.hooks.afterCompile.tap("AutomaticPrefetchPlugin", compilation => {
lastModules = [];
for (const m of compilation.modules) {
if (m instanceof NormalModule) {
lastModules.push({
context: m.context,
request: m.request
});
}
}
});
2018-02-25 09:00:20 +08:00
compiler.hooks.make.tapAsync(
"AutomaticPrefetchPlugin",
(compilation, callback) => {
if (!lastModules) return callback();
2024-08-02 02:36:27 +08:00
// eslint-disable-next-line unicorn/no-array-for-each
2018-02-25 09:00:20 +08:00
asyncLib.forEach(
lastModules,
(m, callback) => {
compilation.addModuleChain(
2018-02-25 09:00:20 +08:00
m.context || compiler.context,
new PrefetchDependency(`!!${m.request}`),
2018-02-25 09:00:20 +08:00
callback
);
},
err => {
lastModules = null;
callback(err);
}
2018-02-25 09:00:20 +08:00
);
}
);
}
}
module.exports = AutomaticPrefetchPlugin;