你为什么不想为 npm install 使用 `--save` 选项?

Why wouldn't you want to use the `--save` option for npm install?

我阅读了有关使用 --save 选项 here 的信息,它说它将安装的软件包添加到您的 package.json 文件中。但是为什么这不是自动的呢?你不是一直想要这个吗?

我的理解是 node_modules 是实际保存包代码的目录,而 package.json 是您已安装的所有包的 reference/list,因此当您将它推到一个 repo,你只推后者而不是前者,以节省 space。

然后当其他人克隆或分叉您的存储库时,他们将有 package.json 来引用和安装所有必要的包以处理您的项目。

因此,您难道不希望您的包裹总是在 package.json 中以便每个人都能获得所需的东西吗?

对于像 Bowernpm 这样的包管理器,我认为 --save 不是自动的,原因如下:

  1. 并非所有依赖项都是生产依赖项(参见 --save-dev)。
  2. 有时您需要在不更改 package.json 的情况下测试包。
  3. 您可能更愿意在本地安装您的同事在其计算机上全局安装的一些软件包。

未安装 --save 的软件包不被视为依赖项,并保持独立。您可以使用 npm ls 轻松地将它们检测为 无关的包 并使用 npm prune.

立即删除它们

现在,如果您认为无关的软件包是件坏事,您当然可以在每次安装新软件包时使用 --save。出于实际原因,请注意您可以使用 -S 快捷方式而不是 --save。此外,如果您经常忘记使用该选项,您可以在 shell.

中定义一个别名

最后,如果您使用 Yarn,请注意 yarn add 命令会将每个包添加为依赖项。不再有 --save 标志。

引用一位 npm 维护者的话:

In the last couple years, quite a bit has changed here, which renders parts of this issue moot: [...] It’s [...] easy enough to run npm config set save true as an end users. That said, there are still a number of rough spots when making --save the default:

  • While the cognitive load of having to remember --save or --save-dev at install time is an irritating niggle, it does force you to choose at install time whether a package is a dependency or devDependency.
  • Moving packages between sections in package.json is still a little more difficult than it should be, which makes cleaning up after things when you forget to specify that somethi[ng] is a devDependency. [...] I don’t think it’s in the best interests, as a result, to opt everyone into saving everything by default.

(来自 https://github.com/npm/npm/issues/5108