Package Management: npm, package.json, Semantic Versioning and Lockfiles
Manage dependencies like a professional: what npm does, package.json fields, dependencies vs devDependencies, semantic versioning and ^ and ~ ranges, package-lock.json and npm ci, scripts and npx, updating and auditing, supply-chain safety, publishing basics, and pnpm, Yarn and Bun.
kvi5hnuCode Sprout team member7 min readOn this page
Almost every JavaScript project depends on code written by others: a web framework, a date library, a test runner. A package manager finds those packages, downloads them with their own dependencies, records exactly what your project uses, and lets anyone recreate the same setup with one command. npm, which ships with Node, is the default, and its registry at npmjs.com is the largest software package registry in the world. Article 122 introduced the basic commands; this article explains how it all fits together.
package.json
Every project or package has a package.json at its root, created with npm init -y and then edited:
{
"name": "weather-api",
"version": "1.4.0",
"type": "module",
"engines": { "node": ">=22" },
"scripts": {
"start": "node src/server.js",
"dev": "node --watch src/server.js",
"test": "node --test",
"lint": "eslint ."
},
"dependencies": {
"express": "^5.1.0"
},
"devDependencies": {
"eslint": "^10.0.0",
"prettier": "^3.6.0"
}
}
nameandversionidentify the package; they're required only if you publish it.type: "module"makes.jsfiles ES modules (article 122).enginesdocuments which Node versions the project supports.dependenciesare needed to run the code:npm install expressadds one.devDependenciesare needed only to develop it, such as linters, test runners, bundlers and type checkers:npm install -D vitest. A production install withnpm ci --omit=devskips them, which keeps deployments smaller.scriptsare named commands, run withnpm run lint.npm testandnpm startwork withoutrun.
Packages are installed into node_modules/, which can easily contain hundreds of packages, because each dependency brings its own. It's generated, so add it to .gitignore and never edit or commit it.
Semantic versioning and ranges
npm packages use semantic versioning (semver): MAJOR.MINOR.PATCH, such as 5.1.4.
- PATCH (5.1.4): bug fixes only.
- MINOR (5.1.0): new features, backward compatible.
- MAJOR (5.0.0): breaking changes; your code may need updating.
- Versions below
1.0.0signal an unstable API, where even a minor bump may break things. Prerelease versions like5.1.0-beta.1are only installed when requested explicitly.
package.json stores ranges, not exact versions, so you get fixes automatically:
| Range | Accepts | Meaning |
|---|---|---|
^4.17.0 (npm's default) | >=4.17.0 <5.0.0 | minor and patch updates |
~4.17.0 | >=4.17.0 <4.18.0 | patch updates only |
4.17.21 | exactly that version | pinned |
^0.3.1 | >=0.3.1 <0.4.0 | for 0.x, the caret is stricter |
>=4.18.0, * | anything newer, anything | rarely a good idea |
The rules are mechanical. A simplified implementation:
// A simplified version of how npm decides whether a version satisfies a range
function parse(v) {
const [major, minor, patch] = v.split("-")[0].split(".").map(Number);
return { major, minor, patch, pre: v.includes("-") };
}
const cmp = (a, b) => a.major - b.major || a.minor - b.minor || a.patch - b.patch;
function satisfies(version, range) {
const v = parse(version);
if (v.pre) return false; // prereleases need an explicit opt-in
if (range === "*") return true;
const op = range.match(/^(\^|~|>=|<)?/)[0];
const r = parse(range.slice(op.length));
if (op === ">=") return cmp(v, r) >= 0;
if (op === "<") return cmp(v, r) < 0;
if (op === "") return cmp(v, r) === 0; // exact pin
if (cmp(v, r) < 0) return false;
if (op === "~") return v.major === r.major && v.minor === r.minor; // patch updates only
// ^: changes that don't modify the leftmost nonzero component
if (r.major > 0) return v.major === r.major;
if (r.minor > 0) return v.major === 0 && v.minor === r.minor;
return v.major === 0 && v.minor === 0 && v.patch === r.patch;
}
const versions = ["4.17.0", "4.17.21", "4.18.2", "5.0.0", "5.1.0-beta.1"];
for (const range of ["^4.17.0", "~4.17.0", "4.17.21", ">=4.18.0", "^0.3.1"]) {
console.log(range.padEnd(9), versions.filter((v) => satisfies(v, range)));
}
console.log("^0.3.1 accepts 0.3.9:", satisfies("0.3.9", "^0.3.1"), "| 0.4.0:", satisfies("0.4.0", "^0.3.1"));
// Picking what to install: the highest version that satisfies the range
const best = (range) => versions.filter((v) => satisfies(v, range)).sort((a, b) => cmp(parse(a), parse(b))).at(-1);
console.log("npm would install for ^4.17.0:", best("^4.17.0"));
^4.17.0 [ '4.17.0', '4.17.21', '4.18.2' ]
~4.17.0 [ '4.17.0', '4.17.21' ]
4.17.21 [ '4.17.21' ]
>=4.18.0 [ '4.18.2', '5.0.0' ]
^0.3.1 []
^0.3.1 accepts 0.3.9: true | 0.4.0: false
npm would install for ^4.17.0: 4.18.2
For any range, npm installs the highest version that satisfies it. Semver is a promise made by package authors, and it's sometimes broken: a "minor" update can still break your code. That's why the exact versions you actually install need to be recorded.
The lockfile

npm install writes package-lock.json, which records the exact version, download location and integrity hash of every package in the entire dependency tree, including dependencies of dependencies. Commit it. Then:
npm ci("clean install") deletesnode_modulesand installs exactly what the lockfile says, failing if it doesn't matchpackage.json. Use it in CI and deployments, so tested and deployed code use identical dependencies.npm install(with no arguments) installs what's listed, updating the lockfile only whenpackage.jsonchanged.- The integrity hashes make npm reject a downloaded package whose contents changed.
Without a lockfile, two developers installing a week apart can get different versions and a bug that only one of them can reproduce.
Everyday commands
npm install # install everything listed (alias: npm i)
npm install zod # add a dependency at the latest version
npm install -D @types/node # add a dev dependency
npm install express@4 # a specific major version
npm uninstall zod # remove a dependency
npm outdated # what's newer than installed
npm update # update within the allowed ranges
npm ls express # why is this package installed, and which version?
npm audit # known vulnerabilities in the tree
npm audit fix # update to fixed versions within ranges
npm run build # run a script
npx eslint . # run a locally installed tool
npm exec --package=cowsay -- cowsay hi # run a package without adding it to the project
- Local tools are installed in
node_modules/.bin. npm scripts and npx put that folder on thePATH, so"lint": "eslint ."works without a global install. Prefer local installs for project tools, so every developer and CI use the same version. Reservenpm install -gfor general-purpose command-line tools. npx some-tooldownloads and runs a package that isn't installed, which is convenient for one-off generators likenpx create-vite, but runs code you haven't reviewed.- Major-version upgrades are deliberate: read the changelog, run
npm install pkg@latest, then run your tests.
Supply-chain safety
Every dependency is code that runs with your permissions, and some packages run install scripts automatically during npm install. Attackers have published typo-named packages (typosquatting), and stolen maintainers' credentials to publish malicious versions of popular packages, including a self-spreading worm that compromised hundreds of npm packages in 2025. Habits that reduce the risk:
- Add dependencies deliberately; a small, widely used, actively maintained package is safer than an obscure one. Check the exact name before installing.
- Commit the lockfile and install with
npm ci, so new versions arrive only through reviewed lockfile changes. - Run
npm auditin CI, and keep dependencies up to date with automated pull requests (Dependabot, Renovate). - Consider disabling install scripts (
npm ci --ignore-scripts, or pnpm, which doesn't run dependencies' install scripts unless you allow them). - If you publish packages, enable two-factor authentication and use trusted publishing from CI with provenance.
Publishing a package
To share code, give package.json a unique name, a version, a description, a license, and the entry points: "exports": { ".": "./src/index.js" } defines what users can import (article 74). Then npm publish uploads it, and npm version patch|minor|major bumps the version according to semver. Packages can also be scoped under an organization (@acme/utils) and published privately.
Alternatives: pnpm, Yarn and Bun
All of these use the same registry and package.json:
- pnpm stores each package version once on disk and links it into projects, making installs fast and space-efficient, and its strict
node_moduleslayout prevents code from importing packages it didn't declare. It's popular for monorepos (several packages in one repository, managed as workspaces). - Yarn pioneered lockfiles and workspaces; its newer versions offer Plug'n'Play installs without
node_modules. - Bun is a JavaScript runtime with a very fast built-in package manager.
A project should use one package manager, recorded in the packageManager field of package.json, with only that manager's lockfile committed. (Corepack, the tool that enforced this field, was bundled with Node up to version 24 and must be installed separately from Node 25 on.)
Common questions
Should package-lock.json be committed?
Yes, for applications and libraries alike. It makes installs reproducible and lets you review dependency changes. Published libraries don't ship it to their users; users' own lockfiles decide the versions.
What's the difference between npm install and npm ci?
npm install resolves ranges and may update the lockfile. npm ci installs exactly the lockfile's versions into a fresh node_modules and fails if package.json and the lockfile disagree. Use npm ci in CI and deployments.
Is it safe to delete node_modules?
Yes. It's fully generated: npm ci or npm install recreates it from package.json and the lockfile. Deleting it is a common fix for a corrupted install.
Summary
package.jsonlistsdependencies(to run),devDependencies(to develop) andscripts;node_modulesis generated and never committed.- Versions follow semver,
MAJOR.MINOR.PATCH.^allows minor and patch updates (stricter below 1.0),~allows patch updates, and an exact version pins. package-lock.jsonrecords the exact tree with integrity hashes; commit it and usenpm ciin CI.- Run local tools with npm scripts and
npx; audit and update dependencies regularly, and treat every new dependency as code you're trusting. - pnpm, Yarn and Bun are alternatives using the same registry; pick one per project.
Practice Questions
package.json says "date-fns": "^3.2.0". Which of these versions can npm install: 3.2.0, 3.6.1, 4.0.0, 3.1.9?
Answer
3.2.0 and 3.6.1. The caret allows any version from 3.2.0 up to, but not including, 4.0.0. 4.0.0 is a new major version, and 3.1.9 is lower than the minimum.
Your CI tests passed, but production broke because a dependency released a buggy minor version between the CI run and the deployment. What practice prevents this?
Answer
Commit package-lock.json and install with npm ci in both CI and deployment. Both then use exactly the same versions, and upgrades happen only through reviewed lockfile changes.
Should TypeScript, ESLint and Vitest go in dependencies or devDependencies, and why?
Answer
devDependencies. They're needed to build, check and test the code, not to run it, so production installs with --omit=dev can skip them.
Previous: Testing JavaScript: Unit Tests, Mocks and Coverage with node, Vitest and Jest
Next: Bundlers and Transpilers: Vite, esbuild, Rollup, webpack, Babel and TypeScript Compilation

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.