异步 load(url, context, nextLoad)
url<string> 由resolve链返回的 URLcontext<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。format<string>shortCircuit<undefined> | <boolean> 表示此钩子意图 终止load钩子链的信号。默认值:falsesource<string> | <ArrayBuffer> | <TypedArray> 供 Node.js 求值的源代码
警告:异步
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 包含由下一个钩子加载的源代码,无论
模块格式如何。