創用 CC 4.0 授權條款

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

除非另有說明,否則以下內容可被視為在原始內容基礎上修改和刪除的結果。

ContextReplacementPlugin

Context 指的是使用表達式的 require 或動態 import(),例如 require('./locale/' + name + '.json')。當遇到這樣的表達式時,Rspack 會推斷目錄 ('./locale/') 和正規表示式 (/^.*\.json$/)。由於名稱在編譯時未知,Rspack 會將每個檔案都包含在 bundle 中作為模組。

ContextReplacementPlugin 允許您覆寫推斷的資訊。有多種方式可以設定此外掛

選項

  • 類型
new rspack.ContextReplacementPlugin(
  resourceRegExp: RegExp,
  newContentResource?: string,
  newContentRecursive?: boolean,
  newContentRegExp?: RegExp
)

如果資源(目錄)符合 resourceRegExp,則外掛會將預設資源、遞迴標記或產生的正規表示式分別替換為 newContentResourcenewContentRecursivenewContextRegExp。如果 newContentResource 是相對的,則會相對於先前的資源解析。

範例

基本使用案例

new rspack.ContextReplacementPlugin(/moment[/\\]locale$/, /de|fr|hu/);

moment/locale 上下文被限制為符合 /de|fr|hu/ 的檔案。因此只會包含這些語言環境(更多資訊請參閱此議題)。

其他選項

newContentResourcenewContentCreateContextMap 參數也可用

new rspack.ContextReplacementPlugin(
  resourceRegExp: RegExp,
  newContentResource: string,
  newContentCreateContextMap: object // mapping runtime-request (userRequest) to compile-time-request (request)
);

這兩個參數可以一起使用,以更精確的方式重新導向請求。newContentCreateContextMap 允許您將執行時請求以物件的形式對應到編譯請求

new rspack.ContextReplacementPlugin(/selector/, './folder', {
  './request': './request',
  './other-request': './new-request',
});