CompatibilityPlugin.js 2.0 KB

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