1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | Author Tobias Koppers @sokra
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | const RequireContextDependency = require("./RequireContextDependency");
|
---|
9 |
|
---|
10 | /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
|
---|
11 | /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
|
---|
12 | /** @typedef {import("../javascript/JavascriptParser").Range} Range */
|
---|
13 |
|
---|
14 | module.exports = class RequireContextDependencyParserPlugin {
|
---|
15 | /**
|
---|
16 | * @param {JavascriptParser} parser the parser
|
---|
17 | * @returns {void}
|
---|
18 | */
|
---|
19 | apply(parser) {
|
---|
20 | parser.hooks.call
|
---|
21 | .for("require.context")
|
---|
22 | .tap("RequireContextDependencyParserPlugin", expr => {
|
---|
23 | let regExp = /^\.\/.*$/;
|
---|
24 | let recursive = true;
|
---|
25 | let mode = "sync";
|
---|
26 | switch (expr.arguments.length) {
|
---|
27 | case 4: {
|
---|
28 | const modeExpr = parser.evaluateExpression(expr.arguments[3]);
|
---|
29 | if (!modeExpr.isString()) return;
|
---|
30 | mode = /** @type {string} */ (modeExpr.string);
|
---|
31 | }
|
---|
32 | // falls through
|
---|
33 | case 3: {
|
---|
34 | const regExpExpr = parser.evaluateExpression(expr.arguments[2]);
|
---|
35 | if (!regExpExpr.isRegExp()) return;
|
---|
36 | regExp = /** @type {RegExp} */ (regExpExpr.regExp);
|
---|
37 | }
|
---|
38 | // falls through
|
---|
39 | case 2: {
|
---|
40 | const recursiveExpr = parser.evaluateExpression(expr.arguments[1]);
|
---|
41 | if (!recursiveExpr.isBoolean()) return;
|
---|
42 | recursive = /** @type {boolean} */ (recursiveExpr.bool);
|
---|
43 | }
|
---|
44 | // falls through
|
---|
45 | case 1: {
|
---|
46 | const requestExpr = parser.evaluateExpression(expr.arguments[0]);
|
---|
47 | if (!requestExpr.isString()) return;
|
---|
48 | const dep = new RequireContextDependency(
|
---|
49 | {
|
---|
50 | request: requestExpr.string,
|
---|
51 | recursive,
|
---|
52 | regExp,
|
---|
53 | mode,
|
---|
54 | category: "commonjs"
|
---|
55 | },
|
---|
56 | /** @type {Range} */ (expr.range)
|
---|
57 | );
|
---|
58 | dep.loc = /** @type {DependencyLocation} */ (expr.loc);
|
---|
59 | dep.optional = Boolean(parser.scope.inTry);
|
---|
60 | parser.state.current.addDependency(dep);
|
---|
61 | return true;
|
---|
62 | }
|
---|
63 | }
|
---|
64 | });
|
---|
65 | }
|
---|
66 | };
|
---|