npm Essentials: Understanding package.json

Adam Sturge | Oct 24, 2023 min read

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

  1. 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"
}
  1. Dependencies:
{
  "dependencies": {
    "express": "^4.17.1",
    "react": "17.0.2"
  },
  "devDependencies": {
    "jest": "^27.0.6",
    "eslint": "^7.32.0"
  }
}
  1. Scripts:
{
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "test": "jest",
    "build": "webpack --mode production",
    "lint": "eslint src/"
  }
}

Common Tasks

  1. Creating a new package.json:
npm init
# Answer the prompts or use defaults with -y flag
npm init -y
  1. Adding custom npm scripts:
# Add this to package.json manually
"scripts": {
  "hello": "echo 'Hello World'"
}

# Run it with
npm run hello
  1. 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 install to 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": true to prevent accidental publication
  • Browse dependencies: Use npm list or a tool like npm-check to 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"
    ]