RequireJsStuffPlugin.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const {
  7. JAVASCRIPT_MODULE_TYPE_AUTO,
  8. JAVASCRIPT_MODULE_TYPE_DYNAMIC
  9. } = require("./ModuleTypeConstants");
  10. const RuntimeGlobals = require("./RuntimeGlobals");
  11. const ConstDependency = require("./dependencies/ConstDependency");
  12. const {
  13. toConstantDependency
  14. } = require("./javascript/JavascriptParserHelpers");
  15. /** @typedef {import("../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
  16. /** @typedef {import("./Compiler")} Compiler */
  17. /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
  18. const PLUGIN_NAME = "RequireJsStuffPlugin";
  19. module.exports = class RequireJsStuffPlugin {
  20. /**
  21. * Apply the plugin
  22. * @param {Compiler} compiler the compiler instance
  23. * @returns {void}
  24. */
  25. apply(compiler) {
  26. compiler.hooks.compilation.tap(
  27. PLUGIN_NAME,
  28. (compilation, { normalModuleFactory }) => {
  29. compilation.dependencyTemplates.set(
  30. ConstDependency,
  31. new ConstDependency.Template()
  32. );
  33. /**
  34. * @param {JavascriptParser} parser the parser
  35. * @param {JavascriptParserOptions} parserOptions options
  36. * @returns {void}
  37. */
  38. const handler = (parser, parserOptions) => {
  39. if (
  40. parserOptions.requireJs === undefined ||
  41. !parserOptions.requireJs
  42. ) {
  43. return;
  44. }
  45. parser.hooks.call
  46. .for("require.config")
  47. .tap(PLUGIN_NAME, toConstantDependency(parser, "undefined"));
  48. parser.hooks.call
  49. .for("requirejs.config")
  50. .tap(PLUGIN_NAME, toConstantDependency(parser, "undefined"));
  51. parser.hooks.expression
  52. .for("require.version")
  53. .tap(
  54. PLUGIN_NAME,
  55. toConstantDependency(parser, JSON.stringify("0.0.0"))
  56. );
  57. parser.hooks.expression
  58. .for("requirejs.onError")
  59. .tap(
  60. PLUGIN_NAME,
  61. toConstantDependency(
  62. parser,
  63. RuntimeGlobals.uncaughtErrorHandler,
  64. [RuntimeGlobals.uncaughtErrorHandler]
  65. )
  66. );
  67. };
  68. normalModuleFactory.hooks.parser
  69. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  70. .tap(PLUGIN_NAME, handler);
  71. normalModuleFactory.hooks.parser
  72. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  73. .tap(PLUGIN_NAME, handler);
  74. }
  75. );
  76. }
  77. };