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


Node.js resolve(specifier, context, defaultResolve)用法及代碼示例

resolve(specifier, context, defaultResolve)

曆史
版本變化
v17.1.0、v16.14.0

添加對導入斷言的支持。

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

resolve 鉤子返回給定模塊說明符和父 URL 的已解析文件 URL,以及可選的格式(例如 'module' )作為對 load 鉤子的提示。如果指定了格式,則 load 鉤子最終負責提供最終的 format 值(並且可以隨意忽略 resolve 提供的提示);如果 resolve 提供 format ,則需要自定義 load 鉤子,即使隻是將值傳遞給 Node.js 默認的 load 鉤子。

模塊說明符是import 語句或import() 表達式中的字符串,父 URL 是導入該模塊的模塊的 URL,如果這是應用程序的主入口點,則為 undefined

context 中的 conditions 屬性是適用於此解析請求的 package exports conditions 條件數組。它們可用於在別處查找條件映射或在調用默認解析邏輯時修改列表。

當前的package exports conditions 總是在傳遞給鉤子的context.conditions 數組中。為了保證調用 defaultResolve 時的默認 Node.js 模塊說明符解析行為,傳遞給它的 context.conditions 數組必須包含最初傳遞給 resolve 鉤子的 context.conditions 數組的所有元素。

/**
 * @param {string} specifier
 * @param {{
 *   conditions: string[],
 *   parentURL: string | undefined,
 * }} context
 * @param {Function} defaultResolve
 * @returns {Promise<{ url: string }>}
 */
export async function resolve(specifier, context, defaultResolve) {
  const { parentURL = null } = context;
  if (Math.random() > 0.5) { // Some condition.
    // For some or all specifiers, do some custom logic for resolving.
    // Always return an object of the form {url: <string>}.
    return {
      url: parentURL ?
        new URL(specifier, parentURL).href :
        new URL(specifier).href,
    };
  }
  if (Math.random() < 0.5) { // Another condition.
    // When calling `defaultResolve`, the arguments can be modified. In this
    // case it's adding another value for matching conditional exports.
    return defaultResolve(specifier, {
      ...context,
      conditions: [...context.conditions, 'another-condition'],
    });
  }
  // Defer to Node.js for all other specifiers.
  return defaultResolve(specifier, context, defaultResolve);
}

相關用法


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