Installing Exact vs Range Versions
What you'll learn: How package.json version ranges and lockfiles work together to determine exactly which package versions land in node_modules.
When you list a dependency in package.json, you typically specify a version range (like ^1.2.3 or ~2.0.0), not an exact version. This range tells npm what versions are acceptable according to semantic versioning rules. For example, ^1.2.3 means "any version from 1.2.3 up to (but not including) 2.0.0."
The Range vs Exact Tension
Think of the version range as a wish list and the lockfile as the shopping receipt. Your package.json says "I'm okay with lodash between 4.17.0 and 5.0.0," but your lockfile records "we actually installed 4.17.21."
When you run npm install:
- With a lockfile present: npm installs the exact versions recorded in the lockfile, ignoring the ranges (unless you explicitly update)
- Without a lockfile: npm resolves the ranges freshly, picking the latest version that satisfies each range
Installing Exact Versions
You can bypass ranges entirely by:
- Using
npm install --save-exact lodash@4.17.21(saves as"lodash": "4.17.21"with no^) - Manually editing
package.jsonto remove range symbols
Even with exact versions in package.json, the lockfile still matters because your dependencies' dependencies use ranges. The lockfile locks down the entire tree.
Why This Matters
Ranges give you flexibility for patch updates, but the lockfile ensures everyone on your team (and CI/CD) gets identical installs. This prevents "works on my machine" problems caused by different minor/patch versions resolving differently.
Key Takeaway: package.json declares acceptable version ranges; the lockfile records the exact versions installed. Together, they balance flexibility with reproducibility.