webpack/lib/AutomaticPrefetchPlugin.js

58 lines
1.3 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
2018-02-11 12:27:09 +08:00
const asyncLib = require("neo-async");
const PrefetchDependency = require("./dependencies/PrefetchDependency");
const NormalModule = require("./NormalModule");
2018-06-21 18:39:48 +08:00
/** @typedef {import("./Compiler.js")} Compiler */
class AutomaticPrefetchPlugin {
2018-06-14 22:51:20 +08:00
/**
* Apply the plugin
2018-06-21 18:39:48 +08:00
* @param {Compiler} compiler Webpack Compiler
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
);
}
);
let lastModules = null;
2018-02-25 09:00:20 +08:00
compiler.hooks.afterCompile.tap("AutomaticPrefetchPlugin", compilation => {
lastModules = compilation.modules
.filter(m => m instanceof NormalModule)
.map(m => ({
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();
asyncLib.forEach(
lastModules,
(m, callback) => {
compilation.prefetch(
m.context || compiler.context,
new PrefetchDependency(m.request),
callback
);
},
callback
);
}
);
}
}
module.exports = AutomaticPrefetchPlugin;