📌  相关文章
📜  package.json 和 package-lock.json 文件之间的区别

📅  最后修改于: 2022-05-13 01:56:49.190000             🧑  作者: Mango

package.json 和 package-lock.json 文件之间的区别

在本文中,我们将了解package.jsonpackage.lock.json之间的主要区别以及它们在 node js 中的需求。

在 Node.js 中, package.json是一个版本控制文件,用于在项目中安装多个包。在初始化节点应用程序时,您会看到应用程序中安装了三个文件,即node_modulespackage.jsonpackage.lock.json

您可以通过运行以下命令来初始化节点项目 -

npm init

初始化后,您的package.json将如下所示。

{
    "name": "Your project name",
    "version": "1.0.0",
    "description": "Your project description",
    "main": "app.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
    },
    "author": "Author name",
    "license": "ISC",
    "dependencies": {
        "dependency1": "^1.4.0",
        "dependency2": "^1.5.2"
    }
}

正如我们在上面看到的,package.json 文件包含有关项目的元数据以及应用程序所需的功能依赖项。

下面是一个典型的package.lock.json文件的样子,

{
    "name": "Your project name",
    "version": "1.0.0",
    "lockfileVersion": 1,
    "requires": true,
    "dependencies": {
        "dependency1": {
            "version": "1.4.0",
            "resolved": 
"https://registry.npmjs.org/dependency1/-/dependency1-1.4.0.tgz",
            "integrity": 
"sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA=="
        },
        "dependency2": {
            "version": "1.5.2",
            "resolved": 
"https://registry.npmjs.org/dependency2/-/dependency2-1.5.2.tgz",
            "integrity": 
"sha512-WOn21V8AhyE1QqVfPIVxe3tupJacq1xGkPTB4iagT6o+P2cAgEOOwIxMftr4+ZCTI6d551ij9j61DFr0nsP2uQ=="
        }
    }
}

但问题是为什么 package.lock.json 在您的项目应用程序中有 package.json 时是必要的。 package.lock.json是为锁定已安装版本的依赖关系而创建的。它将在您的应用程序中安装该软件包的确切最新版本并将其保存在 package.json 中。假设当前软件包的版本是 1.3.2,那么它将保存带有 (^) 符号的版本。这里的 carot(^) 表示,它将支持任何更高版本的主版本 1,例如。 1.2.2。

如果没有 package.lock.json,不同环境下安装的版本可能会有一些差异。为了克服这个问题,创建了 package.lock.json 以在每个环境中都有相同的结果。它应该在 package.json 文件的源代码控制中,因为如果任何其他用户将克隆项目并安装依赖项,那么它将安装与 package.lock.json 完全相同的依赖项以避免差异。

以下是两者之间的主要区别,

package.json

package.lock.json

It contains basic information about the project.It describes the exact tree that was generated to allow subsequent installs to have the identical tree.
It is mandatory for every project.It is automatically generated for those operations where npm modifies either node_modules tree or package.json.
It records important metadata about the project.It allows future devs to install the same dependencies in the project.
It contains information such as name, description, author, script, and dependencies.It contains the name, dependencies, and locked version of the project.