Skip to content

Sync resolve hook does not affect require.resolve() #62692

@Septh

Description

@Septh

Version

v24.14.0

Platform

Microsoft Windows NT 10.0.26200.0 x64 (Windows 11 25H2 Home Edition build 26200.8037)

Subsystem

node:module

What steps will reproduce the bug?

Extending the code @joyeecheung wrote in her initial PR for registerHooks (#55698):

import assert from 'node:assert';
import { registerHooks, createRequire } from 'node:module';
import { writeFileSync } from 'node:fs';

writeFileSync('./bar.js', 'export const id = 123;', 'utf8');

registerHooks({
  resolve(specifier, context, nextResolve) {
    const replaced = specifier.replace('foo', 'bar');
    return nextResolve(replaced, context);
  },
  load(url, context, nextLoad) {
    const result = nextLoad(url, context);
    return {
      ...result,
      source: result.source.toString().replace('123', '456'),
    };
  },
});

// Checks that it works with require.
const require = createRequire(import.meta.url);
const required = require('./foo.js');  // redirected by resolve hook to bar.js
assert.strictEqual(required.id, 456);  // replaced by load hook to 456

// Checks that it works with import.
const imported = await import('./foo.js');  // redirected by resolve hook to bar.js
assert.strictEqual(imported.id, 456);  // replaced by load hook to 456

// ADDED
console.log(import.meta.resolve('./foo.js'))  // ✅ prints the file: url of bar.js
console.log(require.resolve('./foo.js'))      // 🚫 MODULE_NOT_FOUND ./foo.js

How often does it reproduce? Is there a required condition?

Always.

What is the expected behavior? Why is that the expected behavior?

The last console.log statement should print the file path of bar.js.

What do you see instead?

MODULE_NOT_FOUND thrown.

Additional information

This comment did notice the bug already but it seems it didn't get any traction.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions