BasicMatcherRulePlugin.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("../../declarations/WebpackOptions").RuleSetRule} RuleSetRule */
  7. /** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */
  8. /** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */
  9. class BasicMatcherRulePlugin {
  10. /**
  11. * @param {string} ruleProperty the rule property
  12. * @param {string=} dataProperty the data property
  13. * @param {boolean=} invert if true, inverts the condition
  14. */
  15. constructor(ruleProperty, dataProperty, invert) {
  16. this.ruleProperty = ruleProperty;
  17. this.dataProperty = dataProperty || ruleProperty;
  18. this.invert = invert || false;
  19. }
  20. /**
  21. * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler
  22. * @returns {void}
  23. */
  24. apply(ruleSetCompiler) {
  25. ruleSetCompiler.hooks.rule.tap(
  26. "BasicMatcherRulePlugin",
  27. (path, rule, unhandledProperties, result) => {
  28. if (unhandledProperties.has(this.ruleProperty)) {
  29. unhandledProperties.delete(this.ruleProperty);
  30. const value =
  31. rule[/** @type {keyof RuleSetRule} */ (this.ruleProperty)];
  32. const condition = ruleSetCompiler.compileCondition(
  33. `${path}.${this.ruleProperty}`,
  34. value
  35. );
  36. const fn = condition.fn;
  37. result.conditions.push({
  38. property: this.dataProperty,
  39. matchWhenEmpty: this.invert
  40. ? !condition.matchWhenEmpty
  41. : condition.matchWhenEmpty,
  42. fn: this.invert ? v => !fn(v) : fn
  43. });
  44. }
  45. }
  46. );
  47. }
  48. }
  49. module.exports = BasicMatcherRulePlugin;