同一个网址有多个包
🌐 Multiple packages for the same URL
为了应对复杂的提升情况,多个包可能共享相同的URL,这在确定某个导入来自哪个包时会引入歧义:
🌐 To address complex hoisting situations, multiple packages may share the same URL, which introduces ambiguity when determining which package an import originates from:
{
"packages": {
"app-old": {
"url": "./app-old",
"dependencies": {
"lib": "lib-old"
}
},
"app-new": {
"url": "./app-new",
"dependencies": {
"lib": "lib-new"
}
},
"lib-old": {
"url": "./lib",
"dependencies": {
"react": "react-15"
}
},
"lib-new": {
"url": "./lib",
"dependencies": {
"react": "react-18"
}
}
}
} 在上面的示例中,lib-old 和 lib-new 都使用相同的 ./lib 文件夹来存储它们的源文件,唯一的区别在于它们在执行 require 调用或使用 import 时将访问哪个版本的 react。
🌐 In the example above both lib-old and lib-new use the same ./lib folder to
store their sources, the only difference being in which version of react they'll
access when performing require calls or using import.
因为多个包条目共享同一个 URL,所以从该 URL 内的文件解析一个裸标识符是模糊的,除非知道源包的 ID。如果无法确定包 ID(例如,因为调用方没有从之前的解析中传递它),Node.js 就会抛出错误,而不是随便猜。
🌐 Because multiple package entries share the same URL, resolving a bare specifier from a file within that URL is ambiguous unless the originating package ID is known. If the package ID cannot be determined (for example, because the caller did not propagate it from a previous resolution), Node.js will throw an error rather than guess.
为了支持这种模式,开发者必须按包 ID 对模块实例进行键控,并将其从每个解析结果传播到后续的解析请求。这可以确保当 lib 依赖 react 时,运行时知道请求是来自 lib-old 还是 lib-new,从而选择正确的依赖。
🌐 To support this pattern, implementers must key module instances by package ID
and propagate it from each resolution result to subsequent resolution requests.
This ensures that when lib requires react, the runtime knows whether the
request comes from lib-old or lib-new and can select the correct dependency.