DEV Community

Shivaansh Agarwal
Shivaansh Agarwal

Posted on

Use of package-lock.json

  1. Let's create a new directory and initialize it with npm init -y.
    1. This will create a new package.json file.
  2. Let’s say we’re in 2021 and we want to install moment.js in our project.
  3. That time we would’ve done, npm i moment, but to replicate the same let’s install the latest version of this package at that time which was 2.29.0 (Currently latest is 2.29.4). So the command for that will be npm i moment@2.29.0

    1. This will add a new key for moment inside package.json’s dependencies key, with the value as the version number ^2.29.0. It’ll also create package-lock.json and node_modules folder. Inside node_modules folder we can see that the moment library has been added with the same version number, i.e. 2.29.0 & same is in the package-lock.json

    Screenshot 1

  4. Push code to Github along with both package.json & package-lock.json (or simply delete the node_modules folder)

  5. Take a clone of this repo (or simply delete the node_modules folder), and in that run npm i.

    1. Now since the package-lock file is present it’ll simply install the version of moment that is mentioned in that file which is 2.29.0 inside node_modules. So both package.json & package-lock.json will be on the same package as in the screenshot shown above.
    2. This also means that the developer who commited the code, and someone who clones the project let’s say today, when the latest version of moment is 2.29.4, will also install the version 2.29.4 only because of package-lock.json
  6. If we had NOT commited package-lock.json file, but only package.json, when npm i was done, it would have found ^2.29.0 in package.json, but then it would’ve went to npm repository to find if there’s any new minor or patch release after 2.29.0, and since current latest version is 2.29.4, in node_modules this latest version will be installed and also in the newly created package-lock.json file, this version will be present.

    Screenshot 2

Top comments (0)