webpack/lib/async-modules/InferAsyncModulesPlugin.js

72 lines
2.3 KiB
JavaScript
Raw Normal View History

2019-06-05 17:15:25 +08:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const WebpackError = require("../WebpackError");
2019-06-05 18:07:20 +08:00
const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency");
const HarmonyImportSideEffectDependency = require("../dependencies/HarmonyImportSideEffectDependency");
2019-06-05 17:15:25 +08:00
2019-06-05 18:07:20 +08:00
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */
2019-06-05 17:15:25 +08:00
class InferAsyncModulesPlugin {
/**
* @param {Object} options options object
* @param {boolean | "await"=} options.errorOnImport false: no error, true: error when importing async module, "await": error when import async module without import await
*/
constructor({ errorOnImport = false } = {}) {
this.errorOnImport = errorOnImport;
2019-06-05 17:41:53 +08:00
}
2019-06-05 17:15:25 +08:00
/**
2020-04-23 16:48:36 +08:00
* Apply the plugin
* @param {Compiler} compiler the compiler instance
2019-06-05 17:15:25 +08:00
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap("InferAsyncModulesPlugin", compilation => {
const { moduleGraph } = compilation;
compilation.hooks.finishModules.tap(
"InferAsyncModulesPlugin",
modules => {
/** @type {Set<Module>} */
const queue = new Set();
for (const module of modules) {
if (module.buildMeta && module.buildMeta.async) {
queue.add(module);
}
}
for (const module of queue) {
moduleGraph.setAsync(module);
const connections = moduleGraph.getIncomingConnections(module);
for (const connection of connections) {
2019-06-05 17:41:53 +08:00
const dep = connection.dependency;
if (dep instanceof HarmonyImportDependency && connection.active) {
2019-06-05 17:41:53 +08:00
if (
this.errorOnImport &&
2019-06-05 17:41:53 +08:00
dep instanceof HarmonyImportSideEffectDependency &&
(this.errorOnImport === true || !dep.await)
2019-06-05 17:41:53 +08:00
) {
const error = new WebpackError(
this.errorOnImport === true
? "Tried to import async module with import/export (must enable experiments.importAsync to allow this)"
: "Tried to import async module with normal import/export (must use 'import await'/'export await' instead)"
2019-06-05 17:41:53 +08:00
);
error.module = module;
error.loc = dep.loc;
compilation.errors.push(error);
}
2019-06-05 17:15:25 +08:00
queue.add(connection.originModule);
}
}
}
}
);
});
}
}
module.exports = InferAsyncModulesPlugin;