链接
🌐 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.mjs 和 second.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.