package.json
The package.json file describes your project and its dependencies.
Syntax
npm init -ypackage.json is the manifest at the root of every Node project. It records the project's name, version, scripts, and the packages it depends on.
Creating it
Run npm init (or npm init -y to accept all defaults) to generate one.
Key fields
nameandversion— identify the project.main— the entry file.scripts— named commands you can run.dependencies— packages your app needs.
Example
{
"name": "my-app",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node index.js",
"test": "node --test"
},
"dependencies": {
"express": "^4.18.2"
}
}When to use it
- A developer adds `"main": "src/index.js"` to package.json so that `require('my-package')` resolves to the correct entry file.
- The `"engines"` field in package.json prevents junior developers from accidentally running the project on an unsupported Node version.
- An open-source library uses `"exports"` in package.json to expose different entry points for ESM and CJS consumers.
More examples
Minimal package.json
The smallest valid package.json — name, version, and main entry point are the most important fields.
{
"name": "my-app",
"version": "1.0.0",
"description": "A sample Node.js application",
"main": "index.js",
"license": "MIT"
}Scripts and engines fields
Adds `scripts` for common tasks and `engines` to declare the minimum supported Node.js version.
{
"name": "api-server",
"version": "2.0.0",
"scripts": {
"start": "node src/index.js",
"dev": "node --watch src/index.js",
"test": "jest"
},
"engines": {
"node": ">=18.0.0"
}
}Dual CJS/ESM exports map
Uses the `exports` map to serve the ESM build for `import` and the CJS build for `require`.
{
"name": "my-lib",
"version": "1.0.0",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
}
}
Discussion