npm list 如何知道哪些是直接依赖项?

How does npm list know which ones are direct dependencies?

输入这三个命令后直接进入一个新的:

npm install underscore
npm install lodash
npm install express

我得到一个包含许多软件包的 node_modules 目录:

$ ls node_modules

accepts              cookie-signature  encodeurl     forwarded    lodash             mime-db      parseurl        send            underscore
array-flatten        debug             escape-html   fresh        media-typer        mime-types   path-to-regexp  serve-static    unpipe
content-disposition  depd              etag          http-errors  merge-descriptors  ms           proxy-addr      setprototypeof  utils-merge
content-type         destroy           express       inherits     methods            negotiator   qs              statuses        vary
cookie               ee-first          finalhandler  ipaddr.js    mime               on-finished  range-parser    type-is

在使用npm list时,我可以得到一个树结构:

$ npm list
/tmp/play/npm
├─┬ express@4.14.0
│ ├─┬ accepts@1.3.3
│ │ ├─┬ mime-types@2.1.13
│ │ │ └── mime-db@1.25.0
│ │ └── negotiator@0.6.1
│ ├── array-flatten@1.1.1
│ ├── content-disposition@0.5.1
│ ├── content-type@1.0.2
│ ├── cookie@0.3.1
│ ├── cookie-signature@1.0.6
│ ├─┬ debug@2.2.0
│ │ └── ms@0.7.1
│ ├── depd@1.1.0
│ ├── encodeurl@1.0.1
│ ├── escape-html@1.0.3
│ ├── etag@1.7.0
│ ├─┬ finalhandler@0.5.0
│ │ ├── statuses@1.3.1
│ │ └── unpipe@1.0.0
│ ├── fresh@0.3.0
│ ├── merge-descriptors@1.0.1
│ ├── methods@1.1.2
│ ├─┬ on-finished@2.3.0
│ │ └── ee-first@1.1.1
│ ├── parseurl@1.3.1
│ ├── path-to-regexp@0.1.7
│ ├─┬ proxy-addr@1.1.2
│ │ ├── forwarded@0.1.0
│ │ └── ipaddr.js@1.1.1
│ ├── qs@6.2.0
│ ├── range-parser@1.2.0
│ ├─┬ send@0.14.1
│ │ ├── destroy@1.0.4
│ │ ├─┬ http-errors@1.5.1
│ │ │ ├── inherits@2.0.3
│ │ │ └── setprototypeof@1.0.2
│ │ └── mime@1.3.4
│ ├── serve-static@1.11.1
│ ├─┬ type-is@1.6.14
│ │ └── media-typer@0.3.0
│ ├── utils-merge@1.0.0
│ └── vary@1.1.0
├── lodash@4.17.2
└── underscore@1.8.3

我的问题是:从所有这些依赖项中,npm list 如何知道哪些是我的直接依赖项,例如 undersocrelodashexpress?

注意:我没有 package.json 文件。

npm list 命令将以树形结构将所有已安装软件包的版本及其依赖项打印到标准输出。

所以你只安装了三个包

npm install underscore
npm install lodash
npm install express

所有其他包都依赖于 express

它根据模块的依赖关系构建列表。模块的依赖关系在 dependencies 字段中的每个模块的 package.json 中指定。当您安装模块时 npm 会向模块的 package.json 添加一些额外的字段,其中之一是字段 _requiredBy 以在另一个方向上存储依赖项 link 。如果您 运行 npm list 命令它遍历所有模块并读取每个模块 package.json 中的 _requiredBy 字段。

如果您直接安装模块而不将其保存到您的 package.jsonnpm#USER 添加到 _requiredBy 字段以表示您手动安装它并且它不仅仅是其他模块的依赖。然后 npm list 也会在树的根部显示该模块。

你可以使用这个命令:

npm list --depth=0 2>/dev/null