根据NodeJS docs,require
函数具有一个名为LOAD_SELF_REFERENCE
的加载阶段。它具有以下伪代码:
LOAD_SELF_REFERENCE(X, START)
1. Find the closest package scope to START.
2. If no scope was found, return.
3. If the `package.json` has no "exports", return.
4. If the name in `package.json` isn't a prefix of X, throw "not found".
5. Otherwise, load the remainder of X relative to this package as if it was loaded via `LOAD_NODE_MODULES` with a name in `package.json`.
我假设此算法解析模块,这些模块嵌套在与“ require”调用者相同的程序包中。例如,从require("a/x")
调用a/y.js
。
根据(4.),如果package.json
中的名称不是X的前缀,则算法应该抛出错误。因此,我假设以下代码和文件夹结构应该崩溃:
node_modules
|-a
|-package.json
|-a.js
|-b
|-package.json
|-b.js
|-x.js
其中:
node_modules/a/package.json
:
{
"name": "a",
"main": "./a",
"exports": {
".": "./a"
}
}
node_modules/a/a.js
:
require("b/x");
node_modules/b/package.json
:
{
"name": "b",
"main": "./b",
"exports": {
".": "./b",
"./x": "x"
}
}
但是它以某种方式起作用。这是文档中的错误吗?还是我错误地解释了伪代码?
请咨询。谢谢。
似乎这是specification bug。