What is this package-lock.json file and why do I need it?

Let's first talk about package management

What is package management?

"A package management system is a collection of software tools that automate the process of installing, upgrading, configuring, and removing computer programs for a computer's operating system in a consistent manner." https://en.wikipedia.org/wiki/Package_manager

Or in our case it is a Project/application dependency manager (PM/PDM)

Which is "an interactive system for managing the source code dependencies of a single project in a particular language.  That means specifying, retrieving, updating, arranging on disk, and removing sets of dependent source code, in such a way that collective coherency is maintained beyond the termination of any single command. Its output — which is precisely reproducible — is a self-contained source tree that acts as the input to a compiler or interpreter.  "  https://medium.com/@sdboyer/so-you-want-to-write-a-package-manager-4ae9c17d9527

In English Please

A Package Manager (PM) maintains our codes dependencies which includes the entire dependency tree and can reproduce the same dependency tree output given the same dependency tree input.

 

Think of a PM as an idempotent operation (or a pure function), given the input of A it will always return the same output of 1.

 

Consistent Reproducible Builds!

Where does the package-lock file fit into this?

Package Manager states (Inputs/Outputs)

  • Project code: Our source code.
  • Manifest file: package.json file that developers modify. (Directly/Indirectly)
  • Lock file: This is the package-lock.json file that is written by npm with all the necessary information to reproduce the full dependency tree.
  • Dependency code: All of the code named in the lock file arranged on disk to be used by the compiler/interpreter
  • The manifest file (package.json) is the input for our package manager.
  • The lock file (package-lock.json) along with the dependency code is the output we get from the package manager from the given input.

Dependencies over time

So what benefit do we really get from the package-lock file?

Demo Time!

How does npm install/update work then?

The presence of a package lock changes the installation behavior such that:

  1. The module tree described by the package lock is reproduced. This means reproducing the structure described in the file, using the specific files referenced in "resolved" if available, falling back to normal package resolution using "version" if one isn't.
  2. The tree is walked and any missing dependencies are installed in the usual fashion.

Updating Dependencies

Credit & Sources

why-a-package-lock

By Paul Fischer

why-a-package-lock

  • 70