Why must package-lock.json be committed to Git?
BeginnerConceptNode.js builds (npm, package.json)
Answer
Short answer
Because it records the exact version of every package in the dependency tree (often hundreds). Without it, ^4.19.2 in package.json could install 4.19.2 today and 4.21.0 next month, and the dependencies of your dependencies can change too — so builds become unpredictable.
Example of what goes wrong without it
- Monday: CI installs
some-lib 2.3.1. Tests pass. - Thursday:
some-lib 2.4.0is published with a bug. CI installs it. Builds fail — but nobody changed any code.
What the lockfile contains
"node_modules/express": {
"version": "4.19.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz",
"integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q=="
}
The integrity hash also protects you: if a package's contents change, npm refuses to install it.
What to say in the interview
"The lockfile pins the full resolved tree with integrity hashes, so every install is identical and tamper-evident. We commit it and use npm ci so CI fails if someone forgets to update it."
More on Node.js builds (npm, package.json)
What is package.json and what does it contain?BeginnerHow do you build and run a Node.js application?BeginnerWhat is the difference between npm install and npm ci?BeginnerWhat is the difference between dependencies and devDependencies?BeginnerWhat do the ^ and ~ symbols mean in package.json versions?BeginnerWhat are npm scripts and how do you run them?Beginner