Are you using package-lock.json correctly?

this is how we should use npm ci correctly

Photo by Rahul Mishra on Unsplash

Whenever we do a npm install , it does two things:

  1. Add an entry with package name with versioning in package.json with following format.

2. Creates package.lock.json if it not exists, and if it exists, it overrides the versions inside it.
This overriding nature of npm install creates problem, which we will be seeing today and also how to solve it.

Before Jumping 🦘 into the problem, let’s first understand the SYM versioning format in detail:

Key point to note here:
1. If ^ is present in package version, what it does is, it automatically uses the latest Minor and Patch version on each npm install .
2. If ~ is present in package version, what it does is, it automatically uses the latest patch version on each npm install .

The Problem 🤷‍♂️:

Step 1: Bob 🤵 added a package called xyz using npm install xyz .
Step 2: "xyz": "^2.2.1" added in .package.json
Step 3: A entry with zyz:"^2.2.1" created in package.lock.json
Step 4: Bob 🤵 pushes all his code along with package.lock.json to his remote repository.

After some days, xyz package got few patch fixes and received some minor updates.

When new developer Jerry 🕺 comes, he took the code which Bob has pushed in the repository.

Step 1: Jerry 🕺 took the latest pull of the code and a npm install
Step 2: As “^” was present in package.json , it automatically uses latest minor and patch version.
Step 3: package.lock.json is overridden with the new versions.
Step 4: App got broken because specific version
zyz package was required.

Now we have two ways to fix this:

  1. Do not use ^ or ~ before version names, this will make sure same version of package is installed every time.
    Cons: We will be missing out the auto update feature by not utilising npm features.
  2. use npm ci insead of npm install.

When we use npm ci it respects the package.lock.json and only installs the packages with the version specified in the package.lock.json

Requirement: A package.lock.json file should be present in order to use npm ci . Where ci stands for Clean Install.

Thanks for Reading :)

🫶

--

--

राहुल मिश्रा
राहुल मिश्रा

Responses (3)