同步 load(url, context, nextLoad)
🌐 Synchronous 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是必需的。
-
-
返回:<Object>
format<string> 列出的可接受模块格式之一是 下面。shortCircuit<undefined> | <boolean> 一个信号,表示此钩子打算终止load钩子链。默认值:falsesource<string> | <ArrayBuffer> | <TypedArray> 用于评估的 Node.js 源
load 钩子提供了一种方式来定义用于获取已解析 URL 源代码的自定义方法。这允许加载器在潜在情况下避免从磁盘读取文件。它也可以用于将无法识别的格式映射为受支持的格式,例如将 yaml 映射为 module。
🌐 The load hook provides a way to define a custom method for retrieving the
source code of a resolved URL. This would allow a loader to potentially avoid
reading files from disk. It could also be used to map an unrecognized format to
a supported one, for example yaml to module.
import { registerHooks } from 'node:module';
import { Buffer } from 'node:buffer';
function load(url, context, nextLoad) {
// The hook can skip default loading and provide a custom source code.
if (url === 'special-module') {
return {
source: 'export const special = 42;',
format: 'module',
shortCircuit: true, // This is mandatory if nextLoad() is not called.
};
}
// It's possible to modify the source code loaded by the next - possibly default - step,
// for example, replacing 'foo' with 'bar' in the source code of the module.
const result = nextLoad(url, context);
const source = typeof result.source === 'string' ?
result.source : Buffer.from(result.source).toString('utf8');
return {
source: source.replace(/foo/g, 'bar'),
...result,
};
}
registerHooks({ resolve }); 在更高级的场景中,这也可以用来将不受支持的源转换为受支持的源(见下方示例)。
🌐 In a more advanced scenario, this can also be used to transform an unsupported source to a supported one (see Examples below).