0

Is there a way to define a "fallback" rule for Webpack, so that if nothing else matched from .module.rules, then this rule is applied?

I have tried specifying a rule in last position with a very permissive test:, however it seems to take precedence regardless of its position (first, last, also tried withinoneOf).

Example:

  module: {
    rules: [
      {
        oneOf: [
          { test: /\.ts$/i, loader: "ts-loader" },
          { test: /\.ttf$/i, loader: "url-loader" },
          { test: /.+/, loader: "file-loader" }
        ]
      }
    ]
  }

I'd have liked everything that's not a .ts or .ttf to be loaded via file-loader, but actually it seems to be applied even for .ts files for example.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
P Varga
  • 19,174
  • 12
  • 70
  • 108

1 Answers1

-1

That happens because the regular expression in the last test is matching all file extensions, including the ones you would like ignored.

In order to avoid that, you'll need to filter out the known/expected extensions from the catch-all test.

For example:

  module: {
    rules: [
       { test: /\.ts$/i, loader: "ts-loader" },
       { test: /\.ttf$/i, loader: "url-loader" },
       { test: /\.(?!ts|ttf)([\w]+)/i, loader: "file-loader" }
    ]
  }
bamb0ocha
  • 61
  • 1
  • 5
  • But the rules are within a `oneOf` block, shouldn't that only match one rule? I.e. for `.ts` files, first rule matches, so I'd expect it doesn't even try matching the others... – P Varga Nov 15 '20 at 00:43
  • I can only assume `oneOf` is ignored in your example, as there is no main condition. https://webpack.js.org/configuration/module/#ruleoneof – bamb0ocha Nov 15 '20 at 01:21
  • I have edited my answer and removed the `oneOf` bit – bamb0ocha Nov 15 '20 at 01:28
  • Oh, I might be using `oneOf` incorrectly, let me experiment a bit... An "inverse regex" is unfortunately not really an option because the real config contains around 20 rules, some of them with quite complex regexps, exclusions, etc. so creating and maintaining an inverse would be a nightmare – P Varga Nov 15 '20 at 03:31