CC 4.0 授權

本節內容衍生自以下連結的內容,並受 CC BY 4.0 授權條款約束。

若無特別說明,以下內容可視為在原始內容基礎上修改和刪除的結果。

模組

用於決定如何處理專案中不同類型的模組。

  • 類型: Object
  • 預設: {}

module.defaultRules

  • 類型: Rule[]

預設應用於模組的規則陣列。

詳情請參閱 原始碼

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

module.noParse

  • 類型: string | string[] | RegExp | RegExp[] | ((request: string) => boolean)
  • 預設: undefined

保持匹配模組的模組機制不變,例如 module.exportsrequireimport

當用於忽略沒有外部依賴的函式庫時,它很有用,可以提高建置效能。

注意:這些模組仍然會由設定的 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

  • 類型: Object
  • 預設: {}

使用 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

asset 模組的解析器選項。

module.parser.asset.dataUrlCondition

  • 類型: { maxSize: number }
  • 預設: { maxSize: 8096 }

如果模組大小小於或等於 maxSize,則該模組將會被 Base64 編碼,否則將會建立一個檔案。此選項僅適用於 Asset Module 情況。

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

javascript 模組的解析器選項。

module.parser.javascript.dynamicImportMode

  • 類型: 'lazy' | 'eager' | 'weak' | 'lazy-once'
  • 預設:'lazy'

指定動態導入的全局模式,詳情請參閱 webpackMode

module.parser.javascript.dynamicImportPrefetch

  • 類型: boolean | number
  • 預設值:false

指定動態導入的全局預取,詳情請參閱 webpackPrefetch

module.parser.javascript.dynamicImportPreload

  • 類型: boolean | number
  • 預設值:false

指定動態導入的全局預載,詳情請參閱 webpackPreload

module.parser.javascript.dynamicImportFetchPriority

  • 類型: 'low' | 'high' | 'auto'
  • 預設值:'auto'

指定動態導入的全局 fetchPriority,詳情請參閱 webpackFetchPriority

module.parser.javascript.url

  • 類型: true | false | 'relative'
  • 預設值:true

啟用 new URL() 語法的解析。

當使用 'relative' 時,Rspack 會為 new URL() 語法生成相對 URL,即結果 URL 中不包含基本 URL。

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

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

module.parser.javascript.exprContextCritical

  • 類型: boolean | undefined
  • 預設值:true

啟用對完整動態依賴 (import(variable)) 的警告。

module.parser.javascript.wrappedContextCritical

  • 類型: boolean | undefined
  • 預設值:false

啟用對部分動態依賴 (import("./path/to/" + variable)) 的警告。

module.parser.javascript.wrappedContextRegExp

  • 類型: RegExp | undefined
  • 預設值:/.*/

設定用於匹配包裝的動態依賴的正規表示式。

module.parser.javascript.importMeta

  • 類型: boolean
  • 預設值:true

啟用或停用評估 import.meta

module.parser.javascript.exportsPresence

  • 類型: 'error' | 'warn' | 'auto' | false
  • 預設值:'auto'

針對使用不存在的導出和衝突的重新導出發出警告或錯誤。

  • "error":報告錯誤。
  • "warn":報告警告。
  • "auto":根據模組是否為嚴格 ESM,如果是則發出錯誤,否則發出警告。
  • false:停用此功能。

module.parser.javascript.importExportsPresence

  • 類型: 'error' | 'warn' | 'auto' | false

針對使用不存在的導出發出警告或錯誤,預設為 module.parser.javascript.exportsPresence 的設定。

module.parser.javascript.reexportExportsPresence

  • 類型: 'error' | 'warn' | 'auto' | false

針對衝突的重新導出發出警告或錯誤,預設為 module.parser.javascript.exportsPresence 的設定。

module.parser.javascript.strictExportPresence

  • 類型: boolean

當導入的名稱在導入的模組中不存在時,發出錯誤而不是警告。

module.parser.javascript.worker

  • 類型: string[] | boolean

為 Worker 解析提供自訂語法,通常用於支援 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

  • 類型: 'strict' | 'non-strict'

將模組覆寫為嚴格模式或非嚴格模式。

這可能會影響模組的行為(嚴格模式和非嚴格模式之間某些行為不同),因此請謹慎設定此選項。

module.parser["javascript/auto"]

用於 javascript/auto 模組的解析器選項,與 javascript 解析器選項 相同。

module.parser["javascript/dynamic"]

用於 javascript/dynamic 模組的解析器選項,與 javascript 解析器選項 相同。

module.parser["javascript/esm"]

用於 javascript/esm 模組的解析器選項,與 javascript 解析器選項 相同。

module.parser["css/auto"]

用於 css/auto 模組的解析器選項。

警告

此設定僅在 experiments.css = true 時生效。

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

  • 類型: boolean
  • 預設值: true

對 CSS 導出使用 ES 模組具名導出。

當使用 namedExports: true 時,您可以使用命名空間導出或具名導出。

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

當使用 namedExports: false 時,除了命名空間導出和具名導出之外,還可以使用預設導出。

// 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

用於 css 模組的解析器選項。

警告

此設定僅在 experiments.css = true 時生效。

module.parser.css.namedExports

module.parser["css/auto"].namedExports 相同。

module.parser["css/module"]

用於 css/module 模組的解析器選項。

警告

此設定僅在 experiments.css = true 時生效。

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

module.parser["css/auto"].namedExports 相同。

module.generator

  • 類型: Object
  • 預設: {}

使用 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

用於 asset 模組的產生器選項。

module.generator.asset.dataUrl

  • 類型: Object | (options: { content: string, filename: string }) => string
  • 預設: {}

僅適用於模組類型為 'asset''asset/inline' 的模組。

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

當用作函式時,它會為每個模組執行,並且必須返回 data URI 字串。

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
  • 類型: false | 'base64'
  • 預設值: 'base64'

當設定為 'base64' 時,模組來源將使用 Base64 演算法進行編碼。將編碼設定為 false 將停用編碼。僅適用於模組類型為 'asset''asset/inline' 的模組。

module.generator.asset.dataUrl.mimetype
  • 類型: string
  • 預設值: require('mime-types').lookup(ext)

data URI 的 mimetype。預設從模組資源副檔名解析。僅適用於模組類型為 'asset''asset/inline' 的模組。

module.generator.asset.filename

  • 類型: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
  • 預設: undefined
  • 支援的樣板字串: 請查看 output.assetModuleFilename

output.assetModuleFilename 相同。覆寫 output.assetModuleFilename,並且僅適用於 assetasset/resource 模組類型。

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

module.generator.asset.publicPath

  • 類型: string | ((pathData: PathData, assetInfo?: AssetInfo) => string)
  • 預設: undefined

覆寫 output.publicPath,僅適用於模組類型為 'asset''asset/resource' 的模組。

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

module.generator.asset.emit

  • 類型: boolean
  • 預設值: true

是否將資源輸出到磁碟。您可以將此選項設定為 false,以避免在某些情況下(例如 SSR)輸出不必要的文件。

僅適用於模組類型為 'asset''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"]

用於 asset/inline 模組的產生器選項。

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

module.generator["asset"].dataUrl 相同。

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

module.generator["asset"].dataUrl.encoding 相同。

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

module.generator["asset"].dataUrl.mimetype 相同。

module.generator["asset/resource"]

用於 asset/resource 模組的產生器選項。

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

module.generator["asset"].filename 相同。

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

module.generator["asset"].publicPath 相同。

module.generator["css/auto"]

用於 css/auto 模組的產生器選項。

警告

此設定僅在 experiments.css = true 時生效。

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

  • 類型: 'as-is' | 'camel-case' | 'camel-case-only' | 'dashes' | 'dashes-only'
  • 預設值: 'as-is'

自訂如何將 CSS 導出名稱導出到 javascript 模組,例如保持原樣、將它們轉換為駝峰式命名等。

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

  • 類型: boolean
  • 預設值: 在節點環境中為 true,在 Web 環境中為 false

如果為 true,則僅導出從 CSS 到輸出 JavaScript 檔案的識別符號對應,而不將任何樣式表嵌入到樣板中。如果您將 CSS 模組用於預渲染(例如 SSR)會很有用。

如果為 false,則產生樣式表並將它們嵌入到樣板中。

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

  • 類型: string
  • 預設值: [uniqueName]-[id]-[local]

除了在檔案層級模組層級的替換之外,還可以自訂為 CSS 模組產生的本地類別名稱格式,其中也包含 [uniqueName][local]

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

  • 類型: boolean
  • 預設值: true

此設定用於改善 ESM-CJS 互通性的目的。

是否將 __esModule 新增至 CSS 的 exports 中;如果新增,在 esm-cjs 互通時會將其視為 ES 模組,否則將視為 CommonJS 模組。

例如,一個常見的使用案例是,當使用來自第三方元件庫的 CommonJS 輸出時,有時需要新增此設定以確保正確的 esm-cjs 互通,從而獲得正確的 exports (這可以與Rule.test和其他匹配條件一起使用,以便僅為該特定元件庫新增此設定)。

第三方元件庫的原始碼

import style from './style.css';

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

第三方元件庫發布的 CommonJS 格式輸出

'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

css 模組的產生器選項。

警告

此設定僅在 experiments.css = true 時生效。

module.generator.css.exportsOnly

module.generator["css/auto"].exportsOnly相同。

module.generator.css.esModule

module.generator["css/auto"].esModule相同。

module.generator["css/module"]

css/module 模組的產生器選項。

警告

此設定僅在 experiments.css = true 時生效。

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

module.generator["css/auto"].exportsConvention相同。

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

module.generator["css/auto"].exportsOnly相同。

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

module.generator["css/auto"].localIdentName相同。

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

module.generator["css/auto"].esModule相同。

module.rules

  • 類型: Rule[]
  • 預設值: []

規則陣列,用於匹配模組建立時的請求。這些規則可以修改模組的建立行為。它們可以將 Loader 等應用於模組。

Rule

  • 類型: Rule
  • 預設: {}

Rule 定義匹配模組的條件以及處理這些模組的行為。

Rule 行為

定義相應匹配模組的處理行為,例如:

  • 將 Loader 列表應用於這些模組 (Rule.use)
  • 應用模組的類型 (Rule.type)
  • 應用模組的解析配置 (Rule.resolve)

Condition

  • 類型: string | RegExp | Condition[] | LogicalConditions

定義模組的匹配條件,常見的匹配條件包括 resourceresourceQueryincludeexclude

範例:app.js 匯入 ./image.png?inline#foo

  • resource/path/to/image.png,將與 Rule.resource 條件進行匹配
  • resourceQuery?inline,將與 Rule.resourceQuery 條件進行匹配
  • resourceFragment#foo,將與 Rule.resourceFragment 條件進行匹配

Condition 表示匹配給定輸入的形式,它支援以下類型

  • String:給定一個輸入,當輸入字串滿足 startsWith 時,匹配成功。注意:您可以將其視為 input.startsWith(condition)
  • RegExp:給定一個輸入,當輸入字串滿足正規表示式時,匹配成功。注意:您可以將其視為 condition.test(input)
  • Condition[]:條件列表。至少一個條件必須匹配。
  • LogicalConditions:所有條件都必須匹配。
    • { and: Condition[] }:所有條件都必須匹配。
    • { or: Condition[] }:至少一個條件必須匹配。
    • { not: Condition }:所有條件都不能匹配。
  • (value: string) => boolean:如果使用輸入呼叫它並傳回真值,則匹配成功。

Nested Rule

Nested Rule 可以在 Rule.rulesRule.oneOf 屬性下指定。這些規則僅在父規則條件匹配時才會被評估。每個巢狀規則可以包含其自己的條件。

評估順序如下

  1. 父規則
  2. Rule.rules
  3. Rule.oneOf

Rule.exclude

排除所有匹配此條件的模組,並將與資源的絕對路徑(不包含查詢和片段)進行匹配。此選項不能與 Rule.resource 一起出現。

Rule.include

匹配所有與資源絕對路徑(不包含查詢和片段)匹配的模組。此選項不能與 Rule.resource 一起出現。

Rule.resource

匹配所有與此資源匹配的模組,並將與資源(不包含查詢和片段的絕對路徑)進行匹配。此選項不能與 Rule.test 一起出現。

Rule.resourceQuery

匹配所有與資源的查詢匹配的模組。注意:包含 ?,當 Rule.resourceQuery?raw 時,它將匹配 foo?raw 的資源請求

Rule.resourceFragment

匹配所有與資源的片段匹配的模組。注意:包含 #,當 Rule.resourceFragment#abc 時,它將匹配 foo#abc 的資源請求

Rule.test

匹配所有與此資源匹配的模組,並將與資源(不包含查詢和片段的絕對路徑)進行匹配。此選項不能與 Rule.resource 一起出現。

Rule.issuer

匹配所有與此資源匹配的模組,並將與發出當前模組的模組的資源(不包含查詢和片段的絕對路徑)進行匹配。

Rule.issuerLayer

  • 類型: string
  • 預設: undefined

匹配所有與此資源匹配的模組,並將與發出當前模組的模組的層級進行匹配。

警告

此設定僅在experiments.layers = true 時生效。

一個基本範例

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

一個更複雜的範例是與entry options結合使用,以同時建置現代和傳統套件

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

匹配所有與此資源匹配的模組,並將與引入當前模組的相依性類別進行匹配,例如,esm 用於 importimport()cjs 用於 require()url 用於 new URL()url()

Rule.scheme

匹配所有與此資源匹配的模組,並將與資源的 scheme 進行匹配。

例如,您可以使用以下設定將內嵌 data uri 資源視為單獨的資源

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

Rule.mimetype

匹配所有與此資源匹配的模組,並將與資源的 mimetype 進行匹配。

Rule.descriptionData

  • 類型: { [key: string]: Condition }
  • 預設: undefined

descriptionData 選項允許您匹配描述檔(通常為 package.json)中的屬性值,以確定規則應應用於哪些模組。這是根據 package.json 中找到的中繼資料將規則應用於特定模組的有用方法。

descriptionData 中的物件鍵對應於模組的 package.json 中的鍵,例如 nameversion 等。每個鍵都應與一個用於匹配 package.json 資料的Condition相關聯。

例如,下面我們僅將規則應用於 package.json name 中包含 'rspack' 字串的 JavaScript 資源。

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

Rule.with

  • 類型: { [key: string]: Condition }
  • 預設: undefined

with 可以與import attributes結合使用。

例如,以下設定將匹配 { type: "url" },並將匹配模組的 type 更改為 "asset/resource"

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

以下 import 將會匹配

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

應該注意的是,為了讓 Rspack 正確匹配 with 語法,當您使用builtin:swc-loader時,您需要手動啟用 keepImportAttributes 設定以保留 import 屬性

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

警告

此選項已棄用,請改用 Rule.use

Rule.loader

Rule.loaderRule.use: [ { loader } ] 的簡寫。詳情請參閱 Rule.use

Rule.options

Rule.optionsRule.use: [ { options } ] 的簡寫。詳情請參閱 Rule.use

Rule.parser

  • 類型: Object
  • 預設: {}

針對符合規則條件的特定模組的 Parser 選項,這將覆蓋 module.parser 中的 Parser 選項。

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

有關特定 Parser 選項和對應的模組類型,您可以參考 module.parser

Rule.generator

  • 類型: Object
  • 預設: {}

針對符合規則條件的特定模組的 Generator 選項,這將覆蓋 module.generator 中的 Parser 選項。

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

有關特定 Generator 選項和對應的模組類型,您可以參考 module.generator

Rule.sideEffects

  • 類型: boolean

標記模組是否有副作用

Rule.enforce

  • 類型: 'pre' | 'post'

指定 Loader 的類別。

當指定為 'pre' 時,Loader 將在所有其他 Loader 之前執行。

當指定為 'post' 時,Loader 將在所有其他 Loader 之後執行。

Rule.type

  • 類型: 'javascript/auto' | 'typescript' | 'css' | 'css/module' | 'css/auto' | 'json' | 'asset' | 'asset/source' | 'asset/resource' | 'asset/inline'

用於標記符合條件的模組的類型,這會影響 Rspack 內建處理如何處理模組。例如,當模組標記為 'typescript' 時,則該模組將使用 TS Parser/Generator 處理。

  • 'javascript/auto':JavaScript 模組,支援的模組系統:CommonJS、ESM,目前沒有支援 AMD 模組的計畫。
  • 'javascript/esm':JavaScript 模組,視為 ES 模組。
  • 'javascript/dynamic':JavaScript 模組,視為 Script。
  • 'css': CSS 模組
  • 'css/module':CSS Modules 模組
  • 'css/auto':如果檔名符合 /\.module(s)?\.[^.]+$/,則為 CSS Modules 模組,否則為 CSS 模組
  • 'json':JSON 資料模組
  • 'asset' | 'asset/source' | 'asset/resource' | 'asset/inline':請參閱 Asset Module

Rule.layer

  • 類型: string

用於標記符合條件的模組的層。一組模組可以聯合在一個層中,然後可以在分割區塊、統計資料或 entry 選項中使用。

警告

此設定僅在experiments.layers = true 時生效。

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

Rule.use

  • 類型
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;
}

一個陣列,用於傳遞 Loader 套件名稱及其選項。string[] 例如:use: ['svgr-loader']use: [ { loader: 'svgr-loader' } ] 的簡寫。Loader 將以從右到左的順序執行。

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

也可以使用函數

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

根據符合條件的模組設定特定的模組解析選項

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

Rule.rules

  • 類型: Rule[]
  • 預設: undefined

一種 巢狀規則,當父規則符合時也會使用規則陣列。

Rule.oneOf

  • 類型: Rule[]
  • 預設: undefined

一種 巢狀規則,當父規則符合時,只會使用第一個符合條件的規則。

本頁內容