同步 resolve(specifier, context, nextResolve)
specifier<string>context<Object>conditions<string[]> 相关package.json的导出条件importAttributes<Object> 一个键值对对象,表示要导入模块的 属性parentURL<string> | <undefined> 导入此模块的模块,如果是 Node.js 入口点则为 undefined
nextResolve<Function> 链中后续的resolve钩子, 或者是最后一个用户提供的resolve钩子之后的 Node.js 默认resolve钩子specifier<string>context<Object> | <undefined> 省略时,将提供默认值。提供时, 默认值会合并,并优先采用提供的属性。
- 返回:<Object>
format<string> | <null> | <undefined> 给load钩子的提示(可能会被忽略)。 它可以是模块格式(如'commonjs'或'module'),也可以是任意值, 如'css'或'yaml'。importAttributes<Object> | <undefined> 缓存模块时要使用的导入属性 (可选;如果省略,则使用输入值)shortCircuit<undefined> | <boolean> 表示此钩子打算 终止resolve钩子链的信号。默认值:falseurl<string> 此输入解析到的绝对 URL
resolve 钩子链负责告诉 Node.js 在何处查找以及如何
缓存给定的 import 语句、表达式或 require 调用。它可以
选择性地返回一个格式(如 'module')作为给 load 钩子的提示。
如果指定了格式,load 钩子最终负责提供最终的 format 值
(它可以自由忽略 resolve 提供的提示);如果 resolve 提供了 format,
则需要自定义 load 钩子,即使只是为了将该值传递给
Node.js 默认的 load 钩子。
导入类型属性是将已加载模块保存到内部模块缓存时
缓存键的一部分。如果模块应使用与源代码中
不同的属性进行缓存,则 resolve 钩子负责返回
importAttributes 对象。
context 中的 conditions 属性是一个条件数组,
将用于匹配此解析请求的 包导出条件。
它们可用于在其他地方查找条件映射,或在调用默认解析逻辑时
修改该列表。
当前的 包导出条件 总是包含在
传入钩子的 context.conditions 数组中。为了保证调用 defaultResolve 时
默认的 Node.js 模块说明符解析行为,传给它的 context.conditions
数组_必须_包含最初传入 resolve 钩子的 context.conditions
数组的_所有_元素。
import { registerHooks } from 'node:module';
function resolve(specifier, context, nextResolve) {
// 调用 `defaultResolve` 时,可以修改参数。例如,
// 修改说明符或添加适用的导出条件。
if (specifier.includes('foo')) {
specifier = specifier.replace('foo', 'bar');
return nextResolve(specifier, {
...context,
conditions: [...context.conditions, 'another-condition'],
});
}
// 钩子也可以跳过默认解析并提供自定义 URL。
if (specifier === 'special-module') {
return {
url: 'file:///path/to/special-module.mjs',
format: 'module',
shortCircuit: true, // This is mandatory if nextResolve() is not called.
};
}
// 如果不需要自定义,则交由链中的下一个钩子处理,
// 如果这是最后一个用户指定的加载器,则为 Node.js 默认解析。
return nextResolve(specifier);
}
registerHooks({ resolve });