nodejs / nodejs/node

Relative `require()` in `commonjs` source not processed by ESM Loader

オープン
#53,198 コメント 2 件 リアクション 1 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

confirmed-bug loaders
主要言語
JavaScript
スター
122k
フォーク
37.3k
平均マージ
4日 2時間
マージ済み PR(30日)
283

説明

Version

v22.2.0

Platform

Darwin mac.local 23.4.0 Darwin Kernel Version 23.4.0: Fri Mar 15 00:12:49 PDT 2024; root:xnu-10063.101.17~1/RELEASE_ARM64_T6020 arm64

Subsystem

No response

What steps will reproduce the bug?
'use strict';

require('node:module').register(
  'data:text/javascript,' + `
  import assert from 'node:assert';
  
  export ${encodeURIComponent(
    function resolve(specifier, context, nextResolve) {
      console.log({ specifier, context });
      return nextResolve(specifier, context);
    },
  )}
  
  export ${encodeURIComponent(
    function load(url, context, nextLoad) {
      if (url === 'custom:cjs') {
        return {
          format: 'commonjs',
          source: 'console.log(require("./relative"))',
          shortCircuit: true,
        };
      }
      return nextLoad(url, context);
    }
  )}
  `,
);

import('custom:cjs').then(console.log, console.error);
How often does it reproduce? Is there a required condition?

Consistently

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

The load hook doc says:

When a source is provided, all require calls from this module will be processed by the ESM loader with registered resolve and load hooks

https://nodejs.org/api/module.html#resolvespecifier-context-nextresolve:~:text=When%20a%20source,will%20not%20apply.

What do you see instead?

require() calls with relative path are still processed by the CommonJS loader

Error: Cannot find module './relative'
Require stack:
- custom:cjs
    at Module._resolveFilename (node:internal/modules/cjs/loader:1186:15)
    at require (node:internal/modules/esm/translators:195:30)
    at Object.<anonymous> (custom:cjs:1:13)
    at loadCJSModule (node:internal/modules/esm/translators:223:3)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:258:7)
    at ModuleJob.run (node:internal/modules/esm/module_job:262:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:475:24) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ 'custom:cjs' ]
}
Additional information

No response

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、提供された再現手順を Node.js v22.2.0 で実行し、スタックに表示される ESM loader と CommonJS translator のフレームを追跡します。load-hook のドキュメントに記載されているとおり、hook が提供する CommonJS ソースからの相対 require が、登録された resolve および load hook を通じて処理されれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
javascript, node.js
領域
backend
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
42/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。