NPM package.json 文件的主要用途是什么?

What are the main uses for the NPM package.json file?

我从 here 了解到 package.json 文件中的依赖项允许人们安装依赖项,如果他们通过 npm-

安装您的项目

Finally, the dependencies field is used to list all the dependencies of your project that are available on npm. When someone installs your project through npm, all the dependencies listed will be installed as well. Additionally, if someone runs npm install in the root directory of your project, it will install all the dependencies to ./node_modules.

如果有人不在项目的根目录下 运行 npm install,那么所有依赖项将安装到哪里?

此外,如果他们选择通过 Github 克隆该项目怎么办?无论如何它都准备好了,对吧?那么 package.json 文件除了为用户提供有关该项目的元数据之外还有什么用途?

Where will all the dependencies be installed to if someone doesn't run npm install in the root directory of your project?

如果你的意思是 'where will they be installed if you run the command in a different directory',NPM 将向上搜索父目录,直到找到 package.json,然后将依赖项安装到该文件旁边的 node_modules 文件夹中. IE。它们将始终位于项目根目录中。

Also, what if they choose to clone this project through Github instead? It would be ready to go anyway, right? Then at that point what is the purpose of the package.json file besides giving the user meta data about the project?

不是这样的! Node 项目几乎总是有一个 .gitignore 文件,它明确地将 node_modules 排除在版本控制之外,并希望您在下载源代码后 运行 npm install

没有充分的理由将您的依赖关系放在 GitHub 存储库中 - 只要项目遵守 Semantic Versioning (the vast majority of packages do), npm install will never cause incompatible versions to be downloaded, and if you absolutely need to lock down the versions of your dependencies, you can just use npm shrinkwrap.

编辑: 正如 Matt 的评论非常有用地指出的那样,NPM 有几个超越简单元数据的功能 - 我可能最常使用的是 Scripts,它允许您为命令行操作创建项目特定的别名。

这对我有用的一个例子是 运行 连接 Webpack 开发服务器——它在本地安装到我的 devDependencies 项目中(你可以使用 --save-dev option when installing a package), 所以如果我手动执行它,我将不得不输入以下内容:

"./node_modules/.bin/webpack-dev-server" --inline --hot

坦率地说,这会有点痛苦。相反,我可以将它添加到我的 package.json 中(请注意,使用 NPM 脚本时 node_modules/.bin 会自动添加到系统路径中,因此您不需要每次都键入它):

"scripts": {
    "dev": "webpack-dev-server --inline --hot"
}

然后我要做的就是 运行 是:

npm run dev

除了这个简单的用例之外,还有几个 'special' 脚本名称,它们会在某些事件发生时自动调用 - 例如,prepublish 在将包发布到注册表。

每个 Node.js 项目必须包含至少一个 package.json 文件,通常位于项目的根目录中。此文件标识项目并列出您的项目所依赖的包,使您的构建可重现。

您可以使用文本编辑器创建 package.json 文件,但最快的方法是 运行 npm init 命令并向其传递 -y 标志

  npm init -y