RequireJsStuffPlugin.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 {
  12. toConstantDependency
  13. } = require("../javascript/JavascriptParserHelpers");
  14. const ConstDependency = require("./ConstDependency");
  15. /**
  16. * @import {
  17. * JavascriptParserOptions
  18. * } from "../../declarations/WebpackOptions"
  19. */
  20. /** @import Compiler from "../Compiler" */
  21. /** @import JavascriptParser from "../javascript/JavascriptParser" */
  22. const PLUGIN_NAME = "RequireJsStuffPlugin";
  23. module.exports = class RequireJsStuffPlugin {
  24. /**
  25. * Applies the plugin by registering its hooks on the compiler.
  26. * @param {Compiler} compiler the compiler instance
  27. * @returns {void}
  28. */
  29. apply(compiler) {
  30. compiler.hooks.compilation.tap(
  31. PLUGIN_NAME,
  32. (compilation, { normalModuleFactory }) => {
  33. compilation.dependencyTemplates.set(
  34. ConstDependency,
  35. new ConstDependency.Template()
  36. );
  37. /**
  38. * Handles the hook callback for this code path.
  39. * @param {JavascriptParser} parser the parser
  40. * @param {JavascriptParserOptions} parserOptions options
  41. * @returns {void}
  42. */
  43. const handler = (parser, parserOptions) => {
  44. if (
  45. parserOptions.requireJs === undefined ||
  46. !parserOptions.requireJs
  47. ) {
  48. return;
  49. }
  50. parser.hooks.call
  51. .for("require.config")
  52. .tap(PLUGIN_NAME, toConstantDependency(parser, "undefined"));
  53. parser.hooks.call
  54. .for("requirejs.config")
  55. .tap(PLUGIN_NAME, toConstantDependency(parser, "undefined"));
  56. parser.hooks.expression
  57. .for("require.version")
  58. .tap(
  59. PLUGIN_NAME,
  60. toConstantDependency(parser, JSON.stringify("0.0.0"))
  61. );
  62. parser.hooks.expression
  63. .for("requirejs.onError")
  64. .tap(
  65. PLUGIN_NAME,
  66. toConstantDependency(
  67. parser,
  68. RuntimeGlobals.uncaughtErrorHandler,
  69. [RuntimeGlobals.uncaughtErrorHandler]
  70. )
  71. );
  72. };
  73. normalModuleFactory.hooks.parser
  74. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  75. .tap(PLUGIN_NAME, handler);
  76. normalModuleFactory.hooks.parser
  77. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  78. .tap(PLUGIN_NAME, handler);
  79. }
  80. );
  81. }
  82. };