Modules and npm

Lock dependency versions

Understand why package-lock.json records a complete dependency tree and when npm ci is useful.

8 minute lesson

~~~

package.json declares acceptable version ranges. package-lock.json records the exact resolved dependency tree.

For example, a direct dependency range such as ^4.18.0 can accept newer compatible releases. That dependency has its own dependencies and ranges. Without a lockfile, an install next month can resolve a different complete tree even though your package.json did not change.

The lockfile records direct and transitive versions plus resolution and integrity information. Commit it for an application unless the project has a documented policy not to. Review lockfile changes together with the dependency command that caused them.

Use npm install while intentionally changing dependencies. It resolves a valid tree, updates node_modules, and updates the lockfile when needed.

Use a clean install in CI and deployment:

npm ci

npm ci requires an existing lockfile, removes the existing node_modules directory, installs the locked tree, and never rewrites package.json or the lockfile. If the manifests disagree, it fails instead of silently repairing them. That failure protects the evidence you reviewed.

Flags that affect dependency-tree shape must be consistent. If the lockfile was created with a setting such as legacy-peer-deps, commit the matching project configuration rather than relying on one developer to remember the flag.

A lockfile improves reproducibility; it does not make dependencies secure or make every operating system identical. Native and optional packages can still have platform conditions, and known vulnerabilities or compromised releases remain real risks. Pin the Node and npm versions used by automation when exact tooling behavior matters.

Your action is to run npm ci in a disposable project, change one dependency range in package.json without updating the lockfile, and confirm that the next clean install fails. Then use the normal dependency workflow to restore agreement.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →