The package.json file is the central manifest for Node.js projects and npm packages, managing metadata, dependencies, scripts, and build targets.
Basic Manifest Structure
{
"name": "my-awesome-package",
"version": "1.0.0",
"description": "Production-grade utility library",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"bin": {
"mycli": "./bin/cli.js"
},
"keywords": ["node", "api", "tools"],
"author": "Jane Doe <[email protected]>",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
},
"repository": {
"type": "git",
"url": "https://github.com/example/my-awesome-package.git"
}
}
Dependency Types
{
"dependencies": {
"express": "^4.19.2",
"lodash": "~4.17.21"
},
"devDependencies": {
"eslint": "^9.0.0",
"typescript": "^5.4.5"
},
"peerDependencies": {
"react": ">=18.0.0"
},
"optionalDependencies": {
"fsevents": "^2.3.3"
}
}
Version Prefix Rules
1.2.3: Exact version match.^1.2.3: Compatible with version (allows minor/patch upgrades,1.x.x).~1.2.3: Reasonably close (allows patch upgrades only,1.2.x).*: Any available version.
npm Scripts
{
"scripts": {
"prebuild": "rimraf dist",
"build": "tsc -p tsconfig.build.json",
"start": "node dist/index.js",
"test": "vitest run",
"lint": "eslint .",
"prepare": "husky"
}
}
Run defined scripts with npm run <name>. start and test can be run directly with npm start and npm test.
Configuration Variables
Values declared under "config" are accessible to scripts via environment variables prefixed with npm_package_config_:
{
"config": {
"port": "8080"
},
"scripts": {
"server": "echo Server port: $npm_package_config_port"
}
}