CC 4.0 License

The content of this section is derived from the content of the following links and is subject to the CC BY 4.0 license.

The following contents can be assumed to be the result of modifications and deletions based on the original contents if not specifically stated.

Module

Used to decide how to handle different types of modules in a project.

  • Type: Object
  • Default: {}

module.defaultRules

  • Type: Rule[]

An array of rules applied by default for modules.

See source code for details.

rspack.config.js
module.exports = {
  module: {
    defaultRules: [
      '...', // you can use "..." to reference those rules applied by webpack by default
    ],
  },
};

module.noParse

  • Type: string | string[] | RegExp | RegExp[] | ((request: string) => boolean)
  • Default: undefined

Keep module mechanism of the matched modules as-is, such as module.exports, require, import.

It's useful and can boost build performance when used to ignore libraries without external dependencies.

Note: these modules will still be processed by configured loaders.

rspack.config.js
module.exports = {
  module: {
    noParse: /typescript|watermark-dom/,
  },
};
rspack.config.js
module.exports = {
  module: {
    noParse: [require.resolve('typescript'), /watermark-dom/],
  },
};
rspack.config.js
module.exports = {
  module: {
    noParse: request => /typescript|watermark-dom/.test(request),
  },
};

module.parser

  • Type: Object
  • Default: {}

Configure all parsers' options in one place with module.parser.

rspack.config.js
module.exports = {
  module: {
    parser: {
      // Parser options for asset modules
      asset: {
        dataUrlCondition: {
          maxSize: 16192,
        },
      },
      // Parser options for javascript modules
      javascript: {
        dynamicImportMode: 'lazy',
        dynamicImportPrefetch: false,
        dynamicImportPreload: false,
        url: true,
        importMeta: true,
      },
      // Parser options for CSS modules
      css: {
        namedExports: true,
      },
      // Parser options for css/auto modules
      'css/auto': {
        namedExports: true,
      },
      // Parser options for css/module modules
      'css/module': {
        namedExports: true,
      },
    },
  },
};

module.parser.asset

Parser options for asset modules.

module.parser.asset.dataUrlCondition

  • Type: { maxSize: number }
  • Default: { maxSize: 8096 }

If the module size is less than or equal to maxSize, then the module will be Base64 encoded, otherwise a file will be created. This option can be used only for Asset Module scenarios.

rspack.config.js
module.exports = {
  module: {
    parser: {
      asset: {
        dataUrlCondition: {
          // Modules' size smaller than or equal to 4KB and ending with `.png` will be Base64 encoded.
          maxSize: 4 * 1024,
        },
      },
    },
  },
};

module.parser.javascript

Parser options for javascript modules.

module.parser.javascript.dynamicImportMode

  • Type: 'lazy' | 'eager' | 'weak' | 'lazy-once'
  • Default:'lazy'

Specifies global mode for dynamic import, see webpackMode for more details.

module.parser.javascript.dynamicImportPrefetch

  • Type: boolean | number
  • Default:false

Specifies global prefetch for dynamic import, see webpackPrefetch for more details.

module.parser.javascript.dynamicImportPreload

  • Type: boolean | number
  • Default:false

Specifies global preload for dynamic import, see webpackPreload for more details.

module.parser.javascript.dynamicImportFetchPriority

  • Type: 'low' | 'high' | 'auto'
  • Default:'auto'

Specifies global fetchPriority for dynamic import, see webpackFetchPriority for more details.

module.parser.javascript.url

  • Type: true | false | 'relative'
  • Default:true

Enable parsing of new URL() syntax.

When use 'relative', Rspack would generate relative URLs for new URL() syntax, i.e., there's no base URL included in the result URL:

<!-- with 'relative' -->
<img src="icon.svg" />

<!-- without 'relative' -->
<img src="file:///path/to/project/dist/icon.svg" />

module.parser.javascript.exprContextCritical

  • Type: boolean | undefined
  • Default:true

Enable warnings for full dynamic dependencies (import(variable)).

module.parser.javascript.wrappedContextCritical

  • Type: boolean | undefined
  • Default:false

Enable warnings for partial dynamic dependencies (import("./path/to/" + variable)).

module.parser.javascript.wrappedContextRegExp

  • Type: RegExp | undefined
  • Default:/.*/

Set a regular expression to match wrapped dynamic dependencies.

module.parser.javascript.importMeta

  • Type: boolean
  • Default:true

Enable or disable evaluating import.meta.

module.parser.javascript.exportsPresence

  • Type: 'error' | 'warn' | 'auto' | false
  • Default:'auto'

Warn or error for using non-existent exports and conflicting re-exports.

  • "error": Report errors.
  • "warn": Report warnings.
  • "auto": Depending on whether the module is a strict ESM, give an error if it is, otherwise give a warning.
  • false: Disable this feature.

module.parser.javascript.importExportsPresence

  • Type: 'error' | 'warn' | 'auto' | false

Warn or error for using non-existent exports, defaulting to the configuration of module.parser.javascript.exportsPresence.

module.parser.javascript.reexportExportsPresence

  • Type: 'error' | 'warn' | 'auto' | false

Warn or error for conflicting re-exports, defaulting to the configuration of module.parser.javascript.exportsPresence.

module.parser.javascript.strictExportPresence

  • Type: boolean

Emit errors instead of warnings when imported names don't exist in imported module.

module.parser.javascript.worker

  • Type: string[] | boolean

Provide custom syntax for Worker parsing, commonly used to support Worklet:

module.exports = {
  module: {
    parser: {
      javascript: {
        worker: [
          // Supports CSS paintWorklet
          'CSS.paintWorklet.addModule()',
          // Supports AudioWorklet, with the leading '*' indicating the recognition of a variable named 'context', for example:
          // let context = new AudioContext();
          // await context.audioWorklet.addModule(new URL("noise-processor.js", import.meta.url));
          '*context.audioWorklet.addModule()',
          // Extends default syntax: ["Worker", "SharedWorker", "navigator.serviceWorker.register()", "Worker from worker_threads"]
          '...',
        ],
      },
    },
  },
};

module.parser.javascript.overrideStrict

  • Type: 'strict' | 'non-strict'

Override the module to strict or non-strict.

This may affect the behavior of the module (some behaviors differ between strict and non-strict), so please configure this option carefully.

module.parser["javascript/auto"]

Parser options for javascript/auto modules, same as the javascript parser options.

module.parser["javascript/dynamic"]

Parser options for javascript/dynamic modules, same as the javascript parser options.

module.parser["javascript/esm"]

Parser options for javascript/esm modules, same as the javascript parser options.

module.parser["css/auto"]

Parser options for css/auto modules.

WARNING

This configuration will only take effect when experiments.css = true.

module.parser["css/auto"].namedExports

  • Type: boolean
  • Default: true

Use ES modules named export for CSS exports.

When using namedExports: true, you can use namespace export or named export:

// namespace export
import * as classes from './index.module.css';
// named export
import { class1, class2 } from './index.module.css';

When using namedExports: false, in addition to namespace export and named export, default export can also be used:

// namespace export
import * as classes from './index.module.css';
// named export
import { class1, class2 } from './index.module.css';
// default export
import classes from './index.module.css';
// default export and named export
import classes, { class1, class2 } from './index.module.css';

module.parser.css

Parser options for css modules.

WARNING

This configuration will only take effect when experiments.css = true.

module.parser.css.namedExports

Same as module.parser["css/auto"].namedExports.

module.parser["css/module"]

Parser options for css/module modules.

WARNING

This configuration will only take effect when experiments.css = true.

module.parser["css/module"].namedExports

Same as module.parser["css/auto"].namedExports.

module.generator

  • Type: Object
  • Default: {}

Configure all generators' options in one place with module.generator.

rspack.config.js
module.exports = {
  module: {
    generator: {
      // Generator options for asset modules
      asset: {
        dataUrl: {
          encoding: false,
          mimetype: 'base64',
        },
        filename: '[name]-[contenthash][ext]',
        publicPath: 'https://cdn.example.com/',
      },
      // Generator options for asset/inline modules
      'asset/inline': {
        dataUrl: {
          encoding: false,
          mimetype: 'base64',
        },
      },
      // Generator options for asset/resource modules
      'asset/resource': {
        filename: '[name]-[contenthash][ext]',
        publicPath: 'https://cdn.example.com/',
      },
      // Generator options for css/auto modules
      'css/auto': {
        exportsConvention: 'as-is',
        exportsOnly: false,
        localIdentName: '[uniqueName]-[id]-[local]',
        esModule: true,
      },
      // Generator options for `css` modules
      css: {
        exportsOnly: false,
        esModule: true,
      },
      // Generator options for css/module modules
      'css/module': {
        exportsConvention: 'as-is',
        exportsOnly: false,
        localIdentName: '[uniqueName]-[id]-[local]',
        esModule: true,
      },
    },
  },
};

module.generator.asset

Generator options for asset modules.

module.generator.asset.dataUrl

  • Type: Object | (options: { content: string, filename: string }) => string
  • Default: {}

Only for modules with module type 'asset' or 'asset/inline'.

rspack.config.js
module.exports = {
  module: {
    generator: {
      asset: {
        dataUrl: {
          encoding: 'base64',
          mimetype: 'mimetype/png',
        },
      },
    },
  },
};

When used a a function, it executes for every module and must return a data URI string.

rspack.config.js
module.exports = {
  //...
  module: {
    generator: {
      asset: {
        dataUrl: ({ content }) => {
          const svgToMiniDataURI = require('mini-svg-data-uri');
          return svgToMiniDataURI(content);
        },
      },
    },
  },
};
module.generator.asset.dataUrl.encoding
  • Type: false | 'base64'
  • Default: 'base64'

When set to 'base64', module source will be encoded using Base64 algorithm. Setting encoding to false will disable encoding. Only for modules with module type 'asset' or 'asset/inline'.

module.generator.asset.dataUrl.mimetype
  • Type: string
  • Default: require('mime-types').lookup(ext)

A mimetype for data URI. Resolves from module resource extension by default. Only for modules with module type 'asset' or 'asset/inline'.

module.generator.asset.filename

  • Type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
  • Default: undefined
  • Supported Template string: checkout output.assetModuleFilename

Same as output.assetModuleFilename. Overrides output.assetModuleFilename and only works for asset and asset/resource module types.

rspack.config.js
module.exports = {
  module: {
    generator: {
      asset: {
        filename: 'static/[hash][ext]',
      },
    },
  },
};

module.generator.asset.publicPath

  • Type: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
  • Default: undefined

Override output.publicPath, only for modules with module type 'asset' or 'asset/resource'.

rspack.config.js
module.exports = {
  module: {
    generator: {
      asset: {
        publicPath: 'https://cdn.example.com/',
      },
    },
  },
};

module.generator.asset.emit

  • Type: boolean
  • Default: true

Whether to output assets to disk. You can set this option to false to avoid outputting unnecessary files for some scenarios such as SSR.

Only for modules with module type 'asset' or 'asset/resource'.

  • 'asset':
rspack.config.js
module.exports = {
  module: {
    generator: {
      asset: {
        emit: false,
      },
    },
  },
};
  • 'asset/resource':
rspack.config.js
module.exports = {
  module: {
    generator: {
      'asset/resource': {
        emit: false,
      },
    },
  },
};

module.generator["asset/inline"]

Generator options for asset/inline modules.

module.generator["asset/inline"].dataUrl

Same as module.generator["asset"].dataUrl.

module.generator["asset/inline"].dataUrl.encoding

Same as module.generator["asset"].dataUrl.encoding.

module.generator["asset/inline"].dataUrl.mimetype

Same as module.generator["asset"].dataUrl.mimetype.

module.generator["asset/resource"]

Generator options for asset/resource modules.

module.generator["asset/resource"].filename

Same as module.generator["asset"].filename.

module.generator["asset/resource"].publicPath

Same as module.generator["asset"].publicPath.

module.generator["css/auto"]

Generator options for css/auto modules.

WARNING

This configuration will only take effect when experiments.css = true.

module.generator["css/auto"].exportsConvention

  • Type: 'as-is' | 'camel-case' | 'camel-case-only' | 'dashes' | 'dashes-only'
  • Default: 'as-is'

Customize how CSS export names are exported to javascript modules, such as keeping them as is, transforming them to camel case, etc.

module.generator["css/auto"].exportsOnly

  • Type: boolean
  • Default: true for node environments, false for web environments.

If true, only exports the identifier mappings from CSS into the output JavaScript files, without embedding any stylesheets in the template. Useful if you are using CSS Modules for pre-rendering (e.g. SSR).

If false, generate stylesheets and embed them in the template.

module.generator["css/auto"].localIdentName

  • Type: string
  • Default: [uniqueName]-[id]-[local]

Customize the format of the local class names generated for CSS modules, besides the substitutions at File-level and Module-level, also include [uniqueName] and [local].

module.generator["css/auto"].esModule

  • Type: boolean
  • Default: true

This configuration is available for improved ESM-CJS interoperability purposes.

Whether to add __esModule to the exports of CSS; if added, it will be treated as an ES modules during esm-cjs interop, otherwise, it will be treated as a CommonJS Module.

For example, a common use case, when using the CommonJS output from a third-party component library, it is sometimes necessary to add this configuration to ensure correct esm-cjs interop, to obtain the correct exports (this can be used in conjunction with Rule.test and other matching conditions to add it only for that particular component library).

The original source code of the third-party component library:

import style from './style.css';

export function Button() {
  return <button className={style.btn}></button>;
}

The CommonJS format output published by the third-party component library:

'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true,
});
exports.Button = Button;
var _style = _interopRequireDefault(require('./style.css'));
var _jsxRuntime = require('react/jsx-runtime');
function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
function Button() {
  return /*#__PURE__*/ (0, _jsxRuntime.jsx)('button', {
    className: _style['default'].btn, // <-- Note: After passing through _interopRequireDefault, this need to access default here.
  });
}

module.generator.css

Generator options for css modules.

WARNING

This configuration will only take effect when experiments.css = true.

module.generator.css.exportsOnly

Same as module.generator["css/auto"].exportsOnly.

module.generator.css.esModule

Same as module.generator["css/auto"].esModule.

module.generator["css/module"]

Generator options for css/module modules.

WARNING

This configuration will only take effect when experiments.css = true.

module.generator["css/module"].exportsConvention

Same as module.generator["css/auto"].exportsConvention.

module.generator["css/module"].exportsOnly

Same as module.generator["css/auto"].exportsOnly.

module.generator["css/module"].localIdentName

Same as module.generator["css/auto"].localIdentName.

module.generator["css/module"].esModule

Same as module.generator["css/auto"].esModule.

module.rules

  • Type: (Rule | Falsy)[]
  • Default: []

An array of rules that match the module's requests when it is created. These rules can modify the creation behavior of the module. They can apply Loader, etc. to the module.

Rule

  • Type: Rule
  • Default: {}

Rule defines the conditions for matching a module and the behavior of handling those modules.

Rule behavior

Defines the processing behavior of the corresponding matching module, e.g. :

  • Apply the list of Loader to these modules (Rule.use)
  • Apply the module's type (Rule.type)
  • Apply the module's resolve configuration (Rule.resolve)

Condition

  • Type: string | RegExp | Condition[] | LogicalConditions

Defines a module's match conditions, common matches are resource, resourceQuery, include, and exclude.

Example: app.js imports ./image.png?inline#foo

  • resource is /path/to/image.png, and will match against with Rule.resource Condition
  • resourceQuery is ?inline, and will match against with Rule.resourceQuery Condition
  • resourceFragment is #foo, and will match against with Rule.resourceFragment Condition

Condition represents the form of matching a given input, and it supports the following types:

  • String: Given an input, the match is successful when the input string satisfies startsWith. Note: You can think of it as input.startsWith(condition).
  • RegExp: Given an input, the match is successful when the input string satisfies the regular expression. Note: You can think of it as condition.test(input).
  • Condition[]: A list of conditions. At least one of the Conditions must match.
  • LogicalConditions: All Conditions must match.
    • { and: Condition[] }: All Conditions must match.
    • { or: Condition[] }: At least one of the Conditions must match.
    • { not: Condition }: All Conditions must NOT match.
  • (value: string) => boolean: If it's called with the input and return a truthy value, the match is succeeds.

Nested Rule

Nested Rule can be specified under the properties Rule.rules and Rule.oneOf, These rules are evaluated only when the parent Rule condition matches. Each nested rule can contain its own conditions.

The order of evaluation is as follows:

  1. The parent Rule
  2. Rule.rules
  3. Rule.oneOf

Rule.exclude

Excludes all modules that match this condition and will match against the absolute path of the resource (without query and fragment). This option cannot be present together with Rule.resource.

Rule.include

Matches all modules that match this condition against the absolute path of the resource (without query and fragment). This option cannot be present together with Rule.resource.

Rule.resource

Matches all modules that match this resource, and will match against Resource (the absolute path without query and fragment). This option cannot be present together with Rule.test.

Rule.resourceQuery

Matches all modules that match this resource against the Resource's query. Note: Containing ?, when Rule.resourceQuery is ?raw, it will match the resource request of foo?raw

Rule.resourceFragment

Matches all modules that match this resource against the Resource's fragment. Note: Containing #, when Rule.resourceFragment is #abc, it will match the resource request of foo#abc

Rule.test

Matches all modules that match this resource, and will match against Resource (the absolute path without query and fragment). This option cannot be present together with Rule.resource.

Rule.issuer

Matches all modules that match this resource, and will match against Resource (the absolute path without query and fragment) of the module that issued the current module.

Rule.issuerLayer

  • Type: string
  • Default: undefined

Matches all modules that match this resource, and will match against layer of the module that issued the current module.

WARNING

This configuration will only take effect when experiments.layers = true.

A basic example:

rspack.config.js
module.exports = {
  module: {
    rules: [
      {
        issuerLayer: 'other-layer',
      },
    ],
  },
};

A more complex example is the combination with entry options to build modern and legacy bundles at the same time:

rspack.config.js
module.exports = {
  entry: {
    index: {
      import: './src/index.js',
      layer: 'modern',
    },
    'index-legacy': {
      import: './src/index.js',
      layer: 'legacy',
    },
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        issuerLayer: 'modern',
        options: {
          env: { targets: ['chrome >= 100'] },
        },
      },
      {
        test: /\.js$/,
        issuerLayer: 'legacy',
        options: {
          env: { targets: ['ie >= 11'] },
        },
      },
    ],
  },
  experiments: {
    layers: true,
  },
};

Rule.dependency

Matches all modules that match this resource, and will match against the category of the dependency that introduced the current module, for example esm for import and import(), cjs for require(), url for new URL() and url().

Rule.scheme

Matches all modules that match this resource, and will match against the Resource's scheme.

For example, you can treat the inline data uri resource as a separate resource with the following configuration:

rspack.config.js
module.exports = {
  module: {
    rules: [
      {
        scheme: 'data',
        type: 'asset/resource',
      },
    ],
  },
};

Rule.mimetype

Matches all modules that match this resource, and will match against the Resource's mimetype.

Rule.descriptionData

  • Type: { [key: string]: Condition }
  • Default: undefined

descriptionData option allows you to match values of properties in the description file, typically package.json, to determine which modules a rule should apply to. This is a useful way to apply rules to specific modules based on metadata found in their package.json.

The object keys in descriptionData correspond to keys in the module's package.json, such as name, version, etc. Each key should be associated with a Condition for matching the package.json data.

For example, below we are applying the rule only to JavaScript resources with 'rspack' string included in their package.json name.

rspack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        include: /node_modules/,
        descriptionData: {
          name: packageJsonName => packageJsonName.includes('rspack'),
        },
        // additional rule options...
      },
    ],
  },
};

Rule.with

  • Type: { [key: string]: Condition }
  • Default: undefined

with can be used in conjunction with import attributes.

For example, the following configuration will match { type: "url" } and will change the type of the matched modules to "asset/resource":

rspack.config.js
module.exports = {
  module: {
    rules: [
      {
        with: { type: 'url' },
        type: 'asset/resource',
      },
    ],
  },
};

The following import will match:

import url from './data' with { type: 'url' };
import('./data', { with: { type: 'url' } });

It should be noted that in order for Rspack to properly match the with syntax, when you use builtin:swc-loader, you need to manually enable the keepImportAttributes configuration to preserve import attributes:

rspack.config.js
module.exports = {
  module: {
    rules: [
      {
        with: { type: 'url' },
        type: 'asset/resource',
      },
      {
        test: /\.ts$/,
        exclude: [/node_modules/],
        loader: 'builtin:swc-loader',
        options: {
          jsc: {
            experimental: {
+             keepImportAttributes: true,
            },
            parser: {
              syntax: 'typescript',
            },
          },
        },
        type: 'javascript/auto',
      },
    ],
  },
};

Rule.loaders

WARNING

This option is deprecated, please use Rule.use instead

Rule.loader

Rule.loader is a shortcut to Rule.use: [ { loader } ]. See Rule.use for details.

Rule.options

Rule.options is a shortcut to Rule.use: [ { options } ]. See Rule.use for details.

Rule.parser

  • Type: Object
  • Default: {}

Parser options for the specific modules that matched by the rule conditions, this will override the parser options in module.parser.

rspack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.css/,
        parser: {
          namedExports: false,
        },
        type: 'css/module',
      },
    ],
  },
};

For specific parser options and the corresponding module type, you can refer to module.parser.

Rule.generator

  • Type: Object
  • Default: {}

Generator options for the specific modules that matched by the rule conditions, this will override the parser options in module.generator.

rspack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.png/,
        generator: {
          filename: '[contenthash][ext]',
        },
        type: 'asset',
      },
    ],
  },
};

For specific generator options and the corresponding module type, you can refer to module.generator.

Rule.sideEffects

  • Type: boolean

Flag the module for side effects, this will affect the result of Tree Shaking.

rspack.config.js
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /foo\.js$/,
        sideEffects: false,
      },
    ],
  },
};

Rule.enforce

  • Type: 'pre' | 'post'

Specifies the category of the loader. When not specified, it defaults to normal loader.

There is also an additional category "inlined loader" which are loaders applied inline of the import/require.

When specified as 'pre', the loader will execute before all other loaders.

rspack.config.js
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.js$/,
        enforce: 'pre',
        loader: 'my-pre-loader',
      },
    ],
  },
};

When specified as 'post', the loader will execute after all other loaders.

rspack.config.js
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.js$/,
        enforce: 'post',
        loader: 'my-post-loader',
      },
    ],
  },
};

There are two phases that all loaders enter one after the other:

  • Pitching phase: the pitch method on loaders is called in the order post, inline, normal, pre. See Pitching Loader for details.
  • Normal phase: the default method on loaders is executed in the order pre, normal, inline, post. Transformation on the source code of a module happens in this phase.

Rule.type

  • Type: 'javascript/auto' | 'css' | 'css/module' | 'css/auto' | 'json' | 'asset' | 'asset/source' | 'asset/resource' | 'asset/inline'

Used to mark the type of the matching module, which affects how the module is handled by Rspack's built-in processing.

By default, Rspack will determine the type of the module based on the file extension. For example, .js and .mjs files will be treated as javascript/auto modules, and .json files will be treated as json modules.

For example, if you want to load a .json file through a custom loader, you'd need to set the type to javascript/auto to bypass Rspack's built-in JSON importing.

rspack.config.js
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.json$/,
        type: 'javascript/auto',
        loader: 'custom-json-loader',
      },
    ],
  },
};

All type options are as follows:

  • 'javascript/auto': JavaScript modules, supported module systems: CommonJS, ES modules.
  • 'javascript/esm':JavaScript modules, treated as ES modules.
  • 'javascript/dynamic':JavaScript modules, treated as Script.
  • 'json': JSON data module, see JSON.
  • 'css' | 'css/module' | 'css/auto': CSS module, see Native CSS Support.
  • 'asset' | 'asset/source' | 'asset/resource' | 'asset/inline': Asset module, see Asset Module.

Rule.layer

  • Type: string

Used to mark the layer of the matching module. A group of modules could be united in one layer which could then be used in split chunks, stats or entry options.

WARNING

This configuration will only take effect when experiments.layers = true.

rspack.config.js
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.js$/,
        layer: 'layer-name',
      },
    ],
  },
};

Rule.use

  • Type:
export type RuleSetUse =
  | RuleSetUseItem[]
  | RuleSetUseItem
  | ((ctx: RawFuncUseCtx) => RuleSetUseItem[]);
export type RuleSetUseItem =
  | { loader: string; options: Record<string, any> }
  | string;
export interface RawFuncUseCtx {
  resource?: string;
  realResource?: string;
  resourceQuery?: string;
  issuer?: string;
}

An array to pass the Loader package name and its options. string[] e.g.: use: ['svgr-loader'] is shorthand for use: [ { loader: 'svgr-loader' } ]. Loaders will be executed in right-to-left order.

rspack.config.js
module.exports = {
  //...
  module: {
    rules: [
      {
        //...
        use: [
          'svgr-loader',
          {
            loader: 'svgo-loader',
            options: {
              configFile: false,
            },
          },
        ],
      },
    ],
  },
};

A function can also be used:

rspack.config.js
module.exports = {
  //...
  module: {
    rules: [
      {
        test: /\.svg$/,
        type: 'asset',
        use: info => ({
          loader: 'svgo-loader',
          options: {
            plugins: [
              {
                cleanupIDs: { prefix: basename(info.resource) },
              },
            ],
          },
        }),
      },
    ],
  },
};

Rule.resolve

Set specific module resolve options based on the matching modules

rspack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        resolve: {
          preferRelative: true,
        },
      },
    ],
  },
};

Rule.rules

  • Type: Rule[]
  • Default: undefined

A kind of Nested Rule, an array of Rules that is also used when the parent Rule matches.

Rule.oneOf

  • Type: (Rule | Falsy)[]
  • Default: undefined

A kind of Nested Rule, an array of Rules from which only the first matching Rule is used when the parent Rule matches.

ON THIS PAGE