同步自定义钩子的注销


🌐 Deregistration of synchronous customization hooks

registerHooks() 返回的对象有一个 deregister() 方法,可以用来从链中移除钩子。一旦调用 deregister(),在模块解析或加载过程中,钩子将不再被调用。

🌐 The object returned by registerHooks() has a deregister() method that can be used to remove the hooks from the chain. Once deregister() is called, the hooks will no longer be invoked during module resolution or loading.

这目前仅适用于通过 registerHooks() 注册的同步钩子,而不适用于通过 module.register() 注册的异步钩子。

🌐 This is currently only available for synchronous hooks registered via registerHooks(), not for asynchronous hooks registered via module.register().

import { registerHooks } from 'node:module';

const hooks = registerHooks({
  resolve(specifier, context, nextResolve) {
    console.log('resolve hook called for', specifier);
    return nextResolve(specifier, context);
  },
  load(url, context, nextLoad) {
    return nextLoad(url, context);
  },
});

// At this point, the hooks are active and will be called for
// any subsequent import() or require() calls.
await import('./my-module.mjs');

// Later, remove the hooks from the chain.
hooks.deregister();

// Subsequent loads will no longer trigger the hooks.
await import('./another-module.mjs');const { registerHooks } = require('node:module');

const hooks = registerHooks({
  resolve(specifier, context, nextResolve) {
    console.log('resolve hook called for', specifier);
    return nextResolve(specifier, context);
  },
  load(url, context, nextLoad) {
    return nextLoad(url, context);
  },
});

// At this point, the hooks are active and will be called for
// any subsequent require() calls.
require('./my-module.cjs');

// Later, remove the hooks from the chain.
hooks.deregister();

// Subsequent loads will no longer trigger the hooks.
require('./another-module.cjs');