WebpackIsIncludedPlugin.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. const IgnoreErrorModuleFactory = require("./IgnoreErrorModuleFactory");
  7. const WebpackIsIncludedDependency = require("./dependencies/WebpackIsIncludedDependency");
  8. const {
  9. toConstantDependency
  10. } = require("./javascript/JavascriptParserHelpers");
  11. /** @typedef {import("enhanced-resolve/lib/Resolver")} Resolver */
  12. /** @typedef {import("./Compiler")} Compiler */
  13. /** @typedef {import("./Module")} Module */
  14. /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
  15. class WebpackIsIncludedPlugin {
  16. /**
  17. * @param {Compiler} compiler the compiler instance
  18. * @returns {void}
  19. */
  20. apply(compiler) {
  21. compiler.hooks.compilation.tap(
  22. "WebpackIsIncludedPlugin",
  23. (compilation, { normalModuleFactory }) => {
  24. compilation.dependencyFactories.set(
  25. WebpackIsIncludedDependency,
  26. new IgnoreErrorModuleFactory(normalModuleFactory)
  27. );
  28. compilation.dependencyTemplates.set(
  29. WebpackIsIncludedDependency,
  30. new WebpackIsIncludedDependency.Template()
  31. );
  32. /**
  33. * @param {JavascriptParser} parser the parser
  34. * @returns {void}
  35. */
  36. const handler = parser => {
  37. parser.hooks.call
  38. .for("__webpack_is_included__")
  39. .tap("WebpackIsIncludedPlugin", expr => {
  40. if (
  41. expr.type !== "CallExpression" ||
  42. expr.arguments.length !== 1 ||
  43. expr.arguments[0].type === "SpreadElement"
  44. )
  45. return;
  46. const request = parser.evaluateExpression(expr.arguments[0]);
  47. if (!request.isString()) return;
  48. const dep = new WebpackIsIncludedDependency(
  49. request.string,
  50. expr.range
  51. );
  52. dep.loc = expr.loc;
  53. parser.state.module.addDependency(dep);
  54. return true;
  55. });
  56. parser.hooks.typeof
  57. .for("__webpack_is_included__")
  58. .tap(
  59. "WebpackIsIncludedPlugin",
  60. toConstantDependency(parser, JSON.stringify("function"))
  61. );
  62. };
  63. normalModuleFactory.hooks.parser
  64. .for("javascript/auto")
  65. .tap("WebpackIsIncludedPlugin", handler);
  66. normalModuleFactory.hooks.parser
  67. .for("javascript/dynamic")
  68. .tap("WebpackIsIncludedPlugin", handler);
  69. normalModuleFactory.hooks.parser
  70. .for("javascript/esm")
  71. .tap("WebpackIsIncludedPlugin", handler);
  72. }
  73. );
  74. }
  75. }
  76. module.exports = WebpackIsIncludedPlugin;