IgnorePlugin.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("./Compiler")} Compiler */
  7. class IgnorePlugin {
  8. /**
  9. * @param {RegExp} resourceRegExp A RegExp to test the request against
  10. * @param {RegExp=} contextRegExp A RegExp to test the context (directory) against
  11. */
  12. constructor(resourceRegExp, contextRegExp) {
  13. /** @private @type {RegExp} */
  14. this.resourceRegExp = resourceRegExp;
  15. /** @private @type {RegExp} */
  16. this.contextRegExp = contextRegExp;
  17. /** @private @type {Function} */
  18. this.checkIgnore = this.checkIgnore.bind(this);
  19. }
  20. /**
  21. * @param {string} resource resource
  22. * @returns {boolean} returns true if a "resourceRegExp" exists
  23. * and the resource given matches the regexp.
  24. */
  25. checkResource(resource) {
  26. if (!this.resourceRegExp) {
  27. return false;
  28. }
  29. return this.resourceRegExp.test(resource);
  30. }
  31. /**
  32. * @param {string} context context
  33. * @returns {boolean} returns true if "contextRegExp" does not exist
  34. * or if context matches the given regexp.
  35. */
  36. checkContext(context) {
  37. if (!this.contextRegExp) {
  38. return true;
  39. }
  40. return this.contextRegExp.test(context);
  41. }
  42. /**
  43. * Note that if "contextRegExp" is given, both the "resourceRegExp"
  44. * and "contextRegExp" have to match.
  45. *
  46. * @param {TODO} result result
  47. * @returns {boolean} returns true if result should be ignored
  48. */
  49. checkResult(result) {
  50. if (!result) {
  51. return true;
  52. }
  53. return (
  54. this.checkResource(result.request) && this.checkContext(result.context)
  55. );
  56. }
  57. /**
  58. * @param {TODO} result result
  59. * @returns {TODO|null} returns result or null if result should be ignored
  60. */
  61. checkIgnore(result) {
  62. // check if result is ignored
  63. if (this.checkResult(result)) {
  64. return null;
  65. }
  66. return result;
  67. }
  68. /**
  69. * @param {Compiler} compiler Webpack Compiler
  70. * @returns {void}
  71. */
  72. apply(compiler) {
  73. compiler.hooks.normalModuleFactory.tap("IgnorePlugin", nmf => {
  74. nmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);
  75. });
  76. compiler.hooks.contextModuleFactory.tap("IgnorePlugin", cmf => {
  77. cmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);
  78. });
  79. }
  80. }
  81. module.exports = IgnorePlugin;