异步 load(url, context, nextLoad)


  • url <string> 由 resolve 链返回的 URL
  • context <Object>
    • conditions <string[]> 相关 package.json 的导出条件
    • format <string> | <null> | <undefined> 由 resolve 钩子链可选提供的 格式。作为输入,它可以是任意字符串值;输入值无需 符合下文所述的可接受返回值列表。
    • importAttributes <Object>
  • nextLoad <Function> 链中后续的 load 钩子,或 最后一个用户提供的 load 钩子之后的 Node.js 默认 load 钩子
    • url <string>
    • context <Object> | <undefined> 省略时会提供默认值。提供时,默认值 会与所提供的属性合并,并以所提供的属性优先。在默认的 nextLoad 中,如果 url 所指向的模块没有明确的模块类型信息, 则 context.format 是必需的。
  • 返回:<Promise> 异步版本接受一个包含以下属性的对象, 或者一个将解析为此类对象的 Promise。

警告:异步 load 钩子与 CommonJS 模块的命名空间导出 不兼容。同时使用它们将导致导入得到 一个空对象。未来可能会解决此问题。这不适用于 同步 load 钩子,在这种情况下导出可以照常使用。

异步版本的工作方式与同步版本类似,不过在使用异步 load 钩子时, 为 'commonjs' 省略 source 与提供 source 的效果截然不同:

  • 当提供 source 时,该模块中的所有 require 调用将 由 ESM 加载器使用已注册的 resolve 和 load 钩子处理;该模块 中的所有 require.resolve 调用将由 ESM 加载器 使用已注册的 resolve 钩子处理;只有一部分 CommonJS API 可用(例如没有 require.extensions、没有 require.cache、没有 require.resolve.paths),并且对 CommonJS 模块加载器的猴子补丁 将不会生效。
  • 如果 source 为 undefined 或 null,它将由 CommonJS 模块 加载器处理,且 require/require.resolve 调用不会经过 已注册的钩子。这种对空值 source 的行为是临时的——未来 将不再支持空值 source。

这些注意事项不适用于同步 load 钩子,在这种情况下, 被自定义的 CommonJS 模块可以使用完整的 CommonJS API, 且 require/require.resolve 始终经过已注册的 钩子。

Node.js 内部的异步 load 实现(即 load 链中最后一个钩子的 next 值), 当 format 为 'commonjs' 时,出于向后兼容会为 source 返回 null。 以下是一个示例钩子,它选择 使用非默认行为:

import { readFile } from 'node:fs/promises';

// 异步版本(由 module.register() 接受)不需要此修复;
// 同步版本(由 module.registerHooks() 接受)也不需要。
export async function load(url, context, nextLoad) {
  const result = await nextLoad(url, context);
  if (result.format === 'commonjs') {
    result.source ??= await readFile(new URL(result.responseURL ?? url));
  }
  return result;
} 

这也不适用于同步 load 钩子,在这种情况下,返回的 source 包含由下一个钩子加载的源代码,无论 模块格式如何。