当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。