當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js load(url, context, defaultLoad)用法及代碼示例

load(url, context, defaultLoad)

加載程序 API 正在重新設計。這個鉤子可能會消失,或者它的簽名可能會改變。不要依賴下麵說明的 API。

在此 API 的先前版本中,它被拆分為 3 個單獨的、現已棄用的鉤子(getFormatgetSourcetransformSource)。

load 鉤子提供了一種方法來定義自定義方法來確定應如何解釋、檢索和解析 URL。它還負責驗證導入斷言。

format 的最終值必須是以下之一:

format說明load 返回的 source 的可接受類型
'builtin'加載 Node.js 內置模塊不適用
'commonjs'加載一個 Node.js CommonJS 模塊不適用
'json'加載 JSON 文件{ string , ArrayBuffer , TypedArray }
'module'加載一個 ES 模塊{ string , ArrayBuffer , TypedArray }
'wasm'加載 WebAssembly 模塊{ ArrayBuffer , TypedArray }

source 的值對於類型 'builtin' 被忽略,因為目前無法替換 Node.js 內置(核心)模塊的值。 source 的值對於類型 'commonjs' 被忽略,因為 CommonJS 模塊加載器沒有為 ES 模塊加載器提供覆蓋 CommonJS module return value 的機製。未來可能會克服這一限製。

警告:ESM load 鉤子和來自 CommonJS 模塊的命名空間導出不兼容。嘗試將它們一起使用將導致導入中的空對象。這可能會在未來得到解決。

這些類型都對應於 ECMAScript 中定義的類。

如果基於文本的格式(即 'json''module' )的源值不是字符串,則使用 util.TextDecoder 將其轉換為字符串。

load 鉤子提供了一種方法來定義自定義方法來檢索 ES 模塊說明符的源代碼。這將允許加載程序潛在地避免從磁盤讀取文件。它還可用於將無法識別的格式映射到受支持的格式,例如 yamlmodule

/**
 * @param {string} url
 * @param {{
    format: string,
  }} context If resolve settled with a `format`, that value is included here.
 * @param {Function} defaultLoad
 * @returns {Promise<{
    format: string,
    source: string | ArrayBuffer | SharedArrayBuffer | Uint8Array,
  }>}
 */
export async function load(url, context, defaultLoad) {
  const { format } = context;
  if (Math.random() > 0.5) { // Some condition.
    /*
      For some or all URLs, do some custom logic for retrieving the source.
      Always return an object of the form {
        format: <string>,
        source: <string|buffer>,
      }.
    */
    return {
      format,
      source: '...',
    };
  }
  // Defer to Node.js for all other URLs.
  return defaultLoad(url, context, defaultLoad);
}

在更高級的場景中,這也可用於將不受支持的源轉換為受支持的源(參見下麵的Examples)。

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 load(url, context, defaultLoad)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。