npm Essentials: Understanding package.json
A quick guide on working with package.json in npm projects
Overview
The package.json file is the heart of any Node.js project. It contains metadata about the project and lists its dependencies, scripts, and configurations.
Essential Fields
- Basic project information:
{
"name": "my-awesome-project",
"version": "1.0.0",
"description": "A project that does something awesome",
"main": "index.js",
"author": "Your Name",
"license": "MIT"
}- Dependencies:
{
"dependencies": {
"express": "^4.17.1",
"react": "17.0.2"
},
"devDependencies": {
"jest": "^27.0.6",
"eslint": "^7.32.0"
}
}- Scripts:
{
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "jest",
"build": "webpack --mode production",
"lint": "eslint src/"
}
}Common Tasks
- Creating a new package.json:
npm init
# Answer the prompts or use defaults with -y flag
npm init -y- Adding custom npm scripts:
# Add this to package.json manually
"scripts": {
"hello": "echo 'Hello World'"
}
# Run it with
npm run hello- Setting default configuration:
{
"config": {
"port": 8080
}
}Access in your code with process.env.npm_package_config_port
Common Issues
- Version conflicts: Use
^(caret) for minor updates,~(tilde) for patch updates, or exact versions for critical dependencies - Missing peer dependencies: Some packages require you to manually install peer dependencies
- Outdated lockfile: If package.json and package-lock.json are out of sync, use
npm installto update the lockfile
Additional Notes
Semantic versioning: npm uses SemVer (Major.Minor.Patch):
^1.2.3: Compatible with 1.x.x (not 2.0.0)~1.2.3: Compatible with 1.2.x (not 1.3.0)1.2.3: Exactly this version
- Private packages: Set
"private": trueto prevent accidental publication - Browse dependencies: Use
npm listor a tool likenpm-checkto review your dependencies Engines: Specify Node.js version requirements:
"engines": { "node": ">=14.0.0", "npm": ">=7.0.0" }Browserslist: Define target browsers for tools like Babel and Autoprefixer:
"browserslist": [ ">0.2%", "not dead", "not op_mini all" ]