链接


¥Chaining

可以多次调用 register

¥It's possible to call register more than once:

// entrypoint.mjs
import { register } from 'node:module';

register('./first.mjs', import.meta.url);
register('./second.mjs', import.meta.url);
await import('./my-app.mjs');// entrypoint.cjs
const { register } = require('node:module');
const { pathToFileURL } = require('node:url');

const parentURL = pathToFileURL(__filename);
register('./first.mjs', parentURL);
register('./second.mjs', parentURL);
import('./my-app.mjs');

在这个例子中,注册的钩子将形成链。如果 first.mjssecond.mjs 都定义了 resolve 钩子,则两者都将按照它们注册的顺序被调用。这同样适用于所有其他钩子。

¥In this example, the registered hooks will form chains. If both first.mjs and second.mjs define a resolve hook, both will be called, in the order they were registered. The same applies to all the other hooks.

注册的钩子也会影响 register 本身。在此示例中,second.mjs 将根据 first.mjs 注册的钩子进行解析和加载。这允许用非 JavaScript 语言编写钩子之类的事情,只要早期注册的加载器是转换为 JavaScript 的加载器即可。

¥The registered hooks also affect register itself. In this example, second.mjs will be resolved and loaded per the hooks registered by first.mjs. This allows for things like writing hooks in non-JavaScript languages, so long as an earlier registered loader is one that transpiles into JavaScript.

无法从定义钩子的模块内调用 register 方法。

¥The register method cannot be called from within the module that defines the hooks.

Node.js 中文网 - 粤ICP备13048890号