CC 4.0 授權

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

以下內容若未特別註明,皆可視為基於原始內容進行修改與刪除後的結果。

Loader Context

Loader Context 代表在 Loader 內部可用的屬性,這些屬性會賦予給 this 屬性。

this.addContextDependency()

function addContextDependency(directory: string): void;

將目錄新增為 Loader 結果的依賴,以便監聽目錄中檔案的任何變更。

this.addDependency()

function addDependency(file: string): void;

將檔案新增為 Loader 結果的依賴,以便監聽它們的任何變更。例如,sass-loaderless-loader 使用此技巧來在導入的樣式檔案變更時重新編譯。

this.dependency()

function dependency(file: string): void;

this.addDependency() 的別名。

this.addMissingDependency()

function addMissingDependency(file: string): void;

將不存在的檔案新增為 Loader 結果的依賴,使其可被監聽。

this.async()

告訴 Rspack 這個 Loader 將被非同步呼叫。傳回 this.callback

this.cacheable()

一個設定可快取標記的函式。

function cacheable(flag: boolean = true): void;

預設情況下,Loader 的處理結果會標記為可快取。呼叫此方法並傳遞 false 會關閉 Loader 快取處理結果的能力。

this.callback()

function callback(
  err: Error | null,
  content: string | Buffer,
  sourceMap?: SourceMap,
  meta?: any,
): void;

一個可以同步或非同步呼叫的函式,以便傳回多個結果。預期的參數如下:

  1. 第一個參數必須是 Errornull,這會將目前模組標記為編譯失敗。
  2. 第二個參數是 stringBuffer,表示模組經過 Loader 處理後的檔案內容。
  3. 第三個參數是可由 Loader 處理的 Source Map。
  4. 第四個參數會被 Rspack 忽略,可以是任何東西(例如,一些中繼資料)。
警告

如果呼叫此函式,您應該傳回 undefined 以避免 Loader 結果模糊不清。

傳遞給 this.callback 的值將會傳遞到鏈中的下一個 Loader。sourceMapmeta 參數是可選的。如果未傳遞它們,則下一個 Loader 將不會收到它們。

this.clearDependencies()

function clearDependencies(): void;

移除 Loader 結果的所有依賴。

this.context

目前模組所在的目錄。

this.data

一個在 pitch 和 normal 階段之間共享的資料物件。

this.emitError()

function emitError(error: Error): void;

發出錯誤。與 Loader 中的 throwthis.callback(err) 不同,它不會將目前模組標記為編譯失敗,它只是將錯誤新增到 Rspack 的編譯中,並在本次編譯結束時顯示在命令列上。

this.emitWarning(warning: Error)

function emitWarning(warning: Error): void;

發出警告。

this.emitFile()

function emitFile(
  name: string,
  content: Buffer | string,
  sourceMap: SourceMap,
): void;

發出一個檔案。

this.getOptions(schema)

提取指定的 Loader 選項,並接受一個可選的 JSON 結構描述作為參數。

this.getResolve()

function getResolve(options: ResolveOptions): resolve;

建立一個類似 this.resolve 的解析器。

this.resolve()

function resolve(
  context: string,
  request: string,
  callback: (err: Error | null, result: string) => void,
): void;

解析一個請求。

  • context 必須是目錄的絕對路徑。此目錄用作解析的起始位置。
  • request 是要解析的請求。
  • callback 是一個提供已解析路徑的回呼函式。

this.mode

Rspack 執行時讀取的 mode 值。

可能的值為:'production''development''none'

this.target

Rspack 執行時讀取的 target 值。

this.resource

目前模組的路徑字串。例如 '/abc/resource.js?query#hash'

this.resourcePath

目前模組的路徑字串,不包含查詢和片段參數。例如 '/abc/resource.js?query#hash' 中的 '/abc/resource.js'

this.resourceQuery

目前模組的路徑字串的查詢參數。例如 '/abc/resource.js?query#hash' 中的 '?query'

this.resourceFragment

目前模組的路徑字串的片段參數。例如 '/abc/resource.js?query#hash' 中的 '#hash'

this.rootContext

在設定檔中設定專案的目錄

this.sourceMap

是否應該產生 Source Map。

this.getLogger()

function getLogger(name?: string): void;

取得此編譯的記錄器,透過它可以用來記錄訊息。