在应用代码运行之前以编程方式注册钩子
🌐 Registering hooks before application code runs programmatically
或者,可以从入口点调用 registerHooks()。
🌐 Alternatively, registerHooks() can be called from the entry point.
如果入口点需要加载其他模块,并且加载过程需要自定义,请在注册钩子后使用 require() 或动态 import() 来加载它们。不要在注册钩子的同一个模块中使用静态 import 语句来加载需要自定义的模块,因为静态 import 语句会在导入模块中的任何代码运行之前被求值,包括对 registerHooks() 的调用,无论静态 import 语句在导入模块中的位置如何。
🌐 If the entry point needs to load other modules and the loading process needs to be
customized, load them using either require() or dynamic import() after the hooks
are registered. Do not use static import statements to load modules that need to be
customized in the same module that registers the hooks, because static import statements
are evaluated before any code in the importer module is run, including the call to
registerHooks(), regardless of where the static import statements appear in the importer
module.
import { registerHooks } from 'node:module';
registerHooks({ /* implementation of synchronous hooks */ });
// If loaded using static import, the hooks would not be applied when loading
// my-app.mjs, because statically imported modules are all executed before its
// importer regardless of where the static import appears.
// import './my-app.mjs';
// my-app.mjs must be loaded dynamically to ensure the hooks are applied.
await import('./my-app.mjs');const { registerHooks } = require('node:module');
registerHooks({ /* implementation of synchronous hooks */ });
import('./my-app.mjs');
// Or, if my-app.mjs does not have top-level await or it's a CommonJS module,
// require() can also be used:
// require('./my-app.mjs');