GlobMatcherRulePlugin.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Alexander Akait @alexander-akait
  4. */
  5. "use strict";
  6. /**
  7. * @import {
  8. * RuleSetGlob,
  9. * RuleSetGlobs,
  10. * RuleSetRule
  11. * } from "../../declarations/WebpackOptions"
  12. */
  13. /** @import RuleSetCompiler from "./RuleSetCompiler" */
  14. /**
  15. * Defines the keys of types type used by this module.
  16. * @template T
  17. * @template {T[keyof T]} V
  18. * @typedef {import("./RuleSetCompiler").KeysOfTypes<T, V>} KeysOfTypes
  19. */
  20. /** @typedef {KeysOfTypes<RuleSetRule, RuleSetGlob | RuleSetGlobs>} GlobMatcherRuleKeys */
  21. const PLUGIN_NAME = "GlobMatcherRulePlugin";
  22. class GlobMatcherRulePlugin {
  23. /**
  24. * Creates an instance of GlobMatcherRulePlugin.
  25. * @param {GlobMatcherRuleKeys} ruleProperty the rule property
  26. * @param {string=} dataProperty the data property
  27. */
  28. constructor(ruleProperty, dataProperty) {
  29. /** @type {GlobMatcherRuleKeys} */
  30. this.ruleProperty = ruleProperty;
  31. /** @type {string | GlobMatcherRuleKeys} */
  32. this.dataProperty = dataProperty || ruleProperty;
  33. }
  34. /**
  35. * Applies the plugin by registering its hooks on the compiler.
  36. * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler
  37. * @returns {void}
  38. */
  39. apply(ruleSetCompiler) {
  40. ruleSetCompiler.hooks.rule.tap(
  41. PLUGIN_NAME,
  42. (path, rule, unhandledProperties, result) => {
  43. if (unhandledProperties.has(this.ruleProperty)) {
  44. unhandledProperties.delete(this.ruleProperty);
  45. const condition = ruleSetCompiler.compileGlobCondition(
  46. `${path}.${this.ruleProperty}`,
  47. /** @type {RuleSetGlob | RuleSetGlobs} */
  48. (rule[this.ruleProperty])
  49. );
  50. result.conditions.push({
  51. property: this.dataProperty,
  52. matchWhenEmpty: condition.matchWhenEmpty,
  53. fn: condition.fn
  54. });
  55. }
  56. }
  57. );
  58. }
  59. }
  60. module.exports = GlobMatcherRulePlugin;