【发布时间】:2020-05-08 23:44:02
【问题描述】:
根据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”调用者嵌套在同一个包中。例如,从a/y.js 调用require("a/x")。
根据 (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"
}
}
但它以某种方式起作用。 这是文档中的错误吗?还是我错误地解释了伪代码?
请指教。谢谢。
【问题讨论】: