node_module如何解决依赖

How does node_module resolve dependency

假设我有一个 xyz 库(我使用 npm install xyz --save 安装)和项目 abc

node模块如何判断依赖是否应该在

abc/node_modulesabc/node_modules/xyz/node_modules?

如果“根”node_modules.

中存在不兼容的版本,模块将放置在嵌套 node_modules

iRohitBhatia 在对您问题的评论中所说的部分正确。但重要的因素不仅仅是版本 - 而是版本兼容性。


示例:

axios@0.21.1 is dependent on follow-redirects@^1.14.0

如果您这样定义 package.json

{
    "dependencies": {
        "axios": "0.21.1"
    }
}

它将两者安装在同一层。

ls node_modules
axios
follow-redirects
ls node_modules/axios
# there is no nested `node_modules`

但是,如果您的 node_modules 中有 follow-redirects 的不兼容版本,它会将兼容版本安装到嵌套的 node_modules/axios/node_modules.

{
    "dependencies": {
        "follow-redirects": "1.0.0",
        "axios": "0.21.1"
    }
}
ls node_modules
axios
debug
follow-redirects  # the non-compatible `1.0.0` version
ms
ls node_modules/axios/node_modules
follow-redirects  # the compatible version