For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/loader-api/inline-match-resource.md.
close

Inline matchResource

Inline matchResource allows you to dynamically change the matching rules when loading resources. You can set the matchResource for a module specifier by prefixing <match-resource>!=! to the module specifier.

When a matchResource is set, it will be used to match with the module.rules instead of the original resource. This can be useful if further loaders should be applied to the resource, or if the module type needs to be changed.

Tip

It is not recommended to use this syntax in source code. Inline request syntax is intended to only be used by loader generated code. Not following this recommendation will make your code Rspack-specific and non-standard.

Example

file.js
/* STYLE: body { background: red; } */
console.log('yep');

A loader could transform the file into the following file and use the matchResource to apply the user-specified CSS processing rules:

file.js (transformed by loader)
import './file.js.css!=!extract-style-loader/getStyles!./file.js';
console.log('yep');

This will add a dependency to extract-style-loader/getStyles!./file.js and treat the result as file.js.css. Because module.rules has a rule matching /\.css$/ and it will apply to this dependency.

The loader could look like this:

extract-style-loader/index.js
const getStylesLoader = require.resolve('./getStyles');

module.exports = function (source) {
  if (STYLES_REGEXP.test(source)) {
    source = source.replace(STYLES_REGEXP, '');
    return `import ${JSON.stringify(
      this.utils.contextify(
        this.context || this.rootContext,
        `${this.resource}.css!=!${getStylesLoader}!${this.remainingRequest}`,
      ),
    )};${source}`;
  }
  return source;
};
extract-style-loader/getStyles.js
module.exports = function (source) {
  const match = source.match(STYLES_REGEXP);
  return match[0];
};

This page is adapted from webpack documentation under the CC BY 4.0, with modifications.