-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIgnoreAsyncImportsPlugin.js
74 lines (66 loc) · 1.98 KB
/
IgnoreAsyncImportsPlugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* SPDX-FileCopyrightText: 2021-present Kriasoft <[email protected]> */
/* SPDX-License-Identifier: MIT */
const path = require("path");
const webpack = require("webpack");
const ImportDependency = require("./ImportDependency");
/**
* Excludes dynamically imported dependencies from the output bundle.
*
* @typedef {import("webpack").Compiler} Compiler
* @typedef {import("webpack").javascript.JavascriptParser} JavascriptParser
*/
class IgnoreAsyncImportsPlugin {
/**
* Creates a new instance of the plugin.
*
* @param {Object} config Ignore options.
*/
constructor(config = {}) {
this.config = config;
}
/**
* @param {Compiler} compiler
*/
apply(compiler) {
this.name = this.constructor.name;
const handleParser = this.handleParser.bind(this);
compiler.hooks.compilation.tap(
this.name,
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(
ImportDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ImportDependency,
new ImportDependency.Template()
);
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap(this.name, handleParser);
normalModuleFactory.hooks.parser
.for("javascript/dynamic")
.tap(this.name, handleParser);
normalModuleFactory.hooks.parser
.for("javascript/esm")
.tap(this.name, handleParser);
}
);
}
/**
* @param {JavascriptParser} parser
*/
handleParser(parser, parserOptions) {
if (parserOptions.import !== undefined && !parserOptions.import) {
return;
}
// Replace import(...) calls with Promise.resolve(...)
parser.hooks.importCall.tap(this.name, (expr) => {
const dep = new ImportDependency(expr.source.value, expr.range);
dep.loc = expr.loc;
parser.state.module.addDependency(dep);
return false;
});
}
}
module.exports = IgnoreAsyncImportsPlugin;