Referencing external dependency via `package.json` works for ESM, but not CJS
还没有人认领这个 Issue。
- 主要语言
- JavaScript
- 星标
- 122k
- 派生
- 37.4k
- 平均合并
- 4 天 3 小时
- 30 天内合并 PR
- 272
描述
Version
v20.5.1
Platform
Linux vali 6.4.6-76060406-generic #202307241739169092810522.04~d567a38 SMP PREEMPT_DYNAMIC Tue A x86_64 x86_64 x86_64 GNU/Linux
Subsystem
No response
What steps will reproduce the bug?
Clone https://gist.github.com/remcohaszing/25c719651d340d9170dd75428dbcef8e
Given the following files:
// package.json
{
"imports": {
"#path": {
"default": "path"
}
}
}
// index.cjs
require('#path')
// index.mjs
await import('#path')
Now run both scripts.
How often does it reproduce? Is there a required condition?
It reproduces consistently.
What is the expected behavior? Why is that the expected behavior?
Both scripts run and output nothing.
What do you see instead?
Running node index.mjs works fine, but node index.cjs throws:
node:internal/modules/cjs/loader:1018
throw e;
^
TypeError [ERR_INVALID_URL_SCHEME]: The URL must be of scheme file
at new NodeError (node:internal/errors:405:5)
at fileURLToPath (node:internal/url:1397:11)
at finalizeEsmResolution (node:internal/modules/cjs/loader:1059:20)
at Module._resolveFilename (node:internal/modules/cjs/loader:1011:16)
at Module._load (node:internal/modules/cjs/loader:901:27)
at Module.require (node:internal/modules/cjs/loader:1115:19)
at require (node:internal/modules/helpers:130:18)
at Object.<anonymous> (/home/remco/Downloads/foo/index.cjs:1:1)
at Module._compile (node:internal/modules/cjs/loader:1233:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1287:10) {
code: 'ERR_INVALID_URL_SCHEME'
}
Node.js v20.5.1
Referencing a relative path works fine though.
Additional information
There was some discussion in this Twitter thread.
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
使用 gist 中的 package.json、index.cjs 和 index.mjs 重现该问题,然后跟踪 CommonJS 通过 node:internal/modules/cjs/loader 的解析过程,尤其是 finalizeEsmResolution。完成标准是:package.json 中映射到内置 path 的 imports 映射可从两个脚本中运行,且不会出现 ERR_INVALID_URL_SCHEME。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- javascript, node.js
- 领域
- backend
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 活跃
- 描述清晰度
- 基本清楚
- 新手友好度
- 52/100