IgnorePlugin.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. /** @private @type {Function} */
  26. this.checkIgnore = this.checkIgnore.bind(this);
  27. }
  28. /**
  29. * Note that if "contextRegExp" is given, both the "resourceRegExp"
  30. * and "contextRegExp" have to match.
  31. *
  32. * @param {ResolveData} resolveData resolve data
  33. * @returns {false|undefined} returns false when the request should be ignored, otherwise undefined
  34. */
  35. checkIgnore(resolveData) {
  36. if (
  37. "checkResource" in this.options &&
  38. this.options.checkResource &&
  39. this.options.checkResource(resolveData.request, resolveData.context)
  40. ) {
  41. return false;
  42. }
  43. if (
  44. "resourceRegExp" in this.options &&
  45. this.options.resourceRegExp &&
  46. this.options.resourceRegExp.test(resolveData.request)
  47. ) {
  48. if ("contextRegExp" in this.options && this.options.contextRegExp) {
  49. // if "contextRegExp" is given,
  50. // both the "resourceRegExp" and "contextRegExp" have to match.
  51. if (this.options.contextRegExp.test(resolveData.context)) {
  52. return false;
  53. }
  54. } else {
  55. return false;
  56. }
  57. }
  58. }
  59. /**
  60. * Apply the plugin
  61. * @param {Compiler} compiler the compiler instance
  62. * @returns {void}
  63. */
  64. apply(compiler) {
  65. compiler.hooks.normalModuleFactory.tap("IgnorePlugin", nmf => {
  66. nmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);
  67. });
  68. compiler.hooks.contextModuleFactory.tap("IgnorePlugin", cmf => {
  69. cmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);
  70. });
  71. }
  72. }
  73. module.exports = IgnorePlugin;