gpt4 book ai didi

javascript - *实际*使用的是什么版本的 npm 库?

转载 作者:搜寻专家 更新时间:2023-10-31 23:11:05 27 4
gpt4 key购买 nike

我知道 npm 库在安装时可以在分层树中安装同一库的多个版本,如下所示:

a@0.1.0
-> b@1.0
-> c@2.0
-> b@2.0

在上面,版本0.1.0的包a被拉入,它的依赖b@1.0c @2.0。同样,c@2.0 的依赖是拉进来,就是b@2.0

我从某人那里听说,即使包 b 被安装在两个不同的版本中,实际上只有其中一个被加载到内存中并被使用。我还听说 javascript 的 Node 部署与浏览器部署的情况可能不同,也可能不同。

所以我的问题是:是否真的只有b的一个包被加载到内存中?如果是, Node 和浏览器是否都是如此,或者是否存在差异?

最佳答案

Node

可以加载多个版本的 Node 模块/库,具体取决于它们从何处加载。 module loader is covered in depth in the Node.js文档。

require() 调用 caches modules基于解析的文件路径。

require('b') 来自模块 a 将解析为 .../a/node_modules/b

require('b') 来自模块 c 将解析为 .../a/node_modules/c/node_modules/b

因此将为同一个调用加载单独的模块。这可以用一个小例子来证明。

模块 B - node_modules/b/index.js

module.exports = {
VERSION = 'b-0.5.0'
}

模块 C - node_modules/c/index.js

module.exports = {
VERSION: 'c-1.0.0',
BVERSION: require('b').VERSION,
}

模块 C 的 B 副本 - node_modules/c/node_modules/b/index.js

module.exports = {
VERSION: 'b-9.8.7',
}

创建一个程序来输出版本。

console.log('b', require('b').VERSION)
console.log('c', require('c').VERSION)
console.log('cb', require('c').BVERSION)

然后输出版本

→node index.js 
b b-0.5.0
c c-1.0.0
cb b-9.8.7

因此,使用 require('b').VERSION 的不同路径的两个模块会得到不同的值。

遍历

值得注意的是,如果 Node.js require('b') 找不到本地安装的 ./node_modules/b 那么它将向上遍历目录在父 node_modules 目录中寻找 b 的树。

再次使用上面的例子,但是删除了a/node_modules/c/node_modules/b

模块 c 执行 require('b') 但找不到 ...a/node_modules/c/node_modules/b 然后它将进入父 node_modules/ 并寻找 b,在这种情况下它将加载 ...a/node_modules/b 的缓存副本

→node index.js 
b b-0.5.0
c c-1.0.0
cb b-0.5.0

浏览器

浏览器没有 npm 模块的概念。您需要一个支持 CommonJS 模块的加载器,例如 Browserify 或 Webpack。如果加载器不遵守 CommonJS/Node.js 规则,那么它就不可能使用 npm 包。

您应该能够使用您的加载器打包上面的示例并查看它的行为方式。

关于javascript - *实际*使用的是什么版本的 npm 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45655519/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com