UNPKG

2.02 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5"use strict";
6
7const ConstDependency = require("./dependencies/ConstDependency");
8
9const NullFactory = require("./NullFactory");
10
11/** @typedef {import("./Compiler")} Compiler */
12
13class CompatibilityPlugin {
14 /**
15 * Apply the plugin
16 * @param {Compiler} compiler Webpack Compiler
17 * @returns {void}
18 */
19 apply(compiler) {
20 compiler.hooks.compilation.tap(
21 "CompatibilityPlugin",
22 (compilation, { normalModuleFactory }) => {
23 compilation.dependencyFactories.set(ConstDependency, new NullFactory());
24 compilation.dependencyTemplates.set(
25 ConstDependency,
26 new ConstDependency.Template()
27 );
28
29 normalModuleFactory.hooks.parser
30 .for("javascript/auto")
31 .tap("CompatibilityPlugin", (parser, parserOptions) => {
32 if (
33 parserOptions.browserify !== undefined &&
34 !parserOptions.browserify
35 )
36 return;
37
38 parser.hooks.call
39 .for("require")
40 .tap("CompatibilityPlugin", expr => {
41 // support for browserify style require delegator: "require(o, !0)"
42 if (expr.arguments.length !== 2) return;
43 const second = parser.evaluateExpression(expr.arguments[1]);
44 if (!second.isBoolean()) return;
45 if (second.asBool() !== true) return;
46 const dep = new ConstDependency("require", expr.callee.range);
47 dep.loc = expr.loc;
48 if (parser.state.current.dependencies.length > 1) {
49 const last =
50 parser.state.current.dependencies[
51 parser.state.current.dependencies.length - 1
52 ];
53 if (
54 last.critical &&
55 last.options &&
56 last.options.request === "." &&
57 last.userRequest === "." &&
58 last.options.recursive
59 )
60 parser.state.current.dependencies.pop();
61 }
62 parser.state.current.addDependency(dep);
63 return true;
64 });
65 });
66 }
67 );
68 }
69}
70module.exports = CompatibilityPlugin;