IgnorePlugin.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const createSchemaValidation = require("./util/create-schema-validation");
  7. /** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */
  8. /** @typedef {import("./Compiler")} Compiler */
  9. /** @typedef {import("./NormalModuleFactory").ResolveData} ResolveData */
  10. const validate = createSchemaValidation(
  11. require("../schemas/plugins/IgnorePlugin.check.js"),
  12. () => require("../schemas/plugins/IgnorePlugin.json"),
  13. {
  14. name: "Ignore Plugin",
  15. baseDataPath: "options"
  16. }
  17. );
  18. class IgnorePlugin {
  19. /**
  20. * @param {IgnorePluginOptions} options IgnorePlugin options
  21. */
  22. constructor(options) {
  23. validate(options);
  24. this.options = options;
  25. /**
  26. * @private
  27. * @type {Function}
  28. */
  29. this.checkIgnore = this.checkIgnore.bind(this);
  30. }
  31. /**
  32. * Note that if "contextRegExp" is given, both the "resourceRegExp"
  33. * and "contextRegExp" have to match.
  34. *
  35. * @param {ResolveData} resolveData resolve data
  36. * @returns {false|undefined} returns false when the request should be ignored, otherwise undefined
  37. */
  38. checkIgnore(resolveData) {
  39. if (
  40. "checkResource" in this.options &&
  41. this.options.checkResource &&
  42. this.options.checkResource(resolveData.request, resolveData.context)
  43. ) {
  44. return false;
  45. }
  46. if (
  47. "resourceRegExp" in this.options &&
  48. this.options.resourceRegExp &&
  49. this.options.resourceRegExp.test(resolveData.request)
  50. ) {
  51. if ("contextRegExp" in this.options && this.options.contextRegExp) {
  52. // if "contextRegExp" is given,
  53. // both the "resourceRegExp" and "contextRegExp" have to match.
  54. if (this.options.contextRegExp.test(resolveData.context)) {
  55. return false;
  56. }
  57. } else {
  58. return false;
  59. }
  60. }
  61. }
  62. /**
  63. * Apply the plugin
  64. * @param {Compiler} compiler the compiler instance
  65. * @returns {void}
  66. */
  67. apply(compiler) {
  68. compiler.hooks.normalModuleFactory.tap("IgnorePlugin", nmf => {
  69. nmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);
  70. });
  71. compiler.hooks.contextModuleFactory.tap("IgnorePlugin", cmf => {
  72. cmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);
  73. });
  74. }
  75. }
  76. module.exports = IgnorePlugin;