What is package.json? Explain its key fields and semantic versioning.
3 minbeginnernodejsnpmpackage-jsonsemverversioning
Quick Answer
package.json is the manifest describing a project: its name/version, entry points (`main`/`exports`), `scripts`, and dependencies. Versions follow semver (MAJOR.MINOR.PATCH); ranges like `^1.2.3` allow compatible minor/patch updates and `~1.2.3` allows only patch updates.
Detailed Answer
Answer:
package.json is the manifest at the root of a Node project.
Common fields:
{
"name": "my-api",
"version": "1.4.2",
"type": "module",
"main": "dist/index.js",
"exports": { ".": "./dist/index.js" },
"scripts": {
"start": "node dist/index.js",
"dev": "node --watch src/index.js",
"test": "jest"
},
"dependencies": { "express": "^4.19.2" },
"devDependencies": { "jest": "^29.7.0" },
"engines": { "node": ">=18" }
}
main/exports— entry points (exportsis the modern, stricter form controlling what's importable).scripts— commands runnable vianpm run <name>(startandtestalso work withoutrun).engines— declares the supported Node version.
Semantic Versioning (semver): MAJOR.MINOR.PATCH
- MAJOR — breaking changes.
- MINOR — new, backward-compatible features.
- PATCH — backward-compatible bug fixes.
Range specifiers:
| Range | Allows | Example matches for 1.4.2 |
|---|---|---|
^1.4.2 | minor + patch (no major) | 1.4.2 → <2.0.0 |
~1.4.2 | patch only | 1.4.2 → <1.5.0 |
1.4.2 | exact | only 1.4.2 |
* / latest | anything | any version |
^ is the npm default because it gets bug fixes and features without (in theory) breaking changes. The exact installed versions are pinned in the lockfile.