Chapter 4: NPM Package Manager
Chapter 4 of 15
Chapter 4: NPM Package Manager
4.1 Package.json
package.json is the configuration file for Node.js projects. It defines project metadata, dependencies, and scripts.
Creating package.json:
// Initialize new project
npm init
// Or use defaults
npm init -y
// Resulting package.json
{
"name": "my-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Package.json Fields:
- name: Package name
- version: Version number (semantic versioning)
- description: Package description
- main: Entry point file
- scripts: Custom npm commands
- dependencies: Production dependencies
- devDependencies: Development dependencies
- keywords: Search keywords
- author: Author information
- license: License type
Scripts Section:
{
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "jest",
"build": "webpack",
"lint": "eslint ."
}
}
// Run scripts
npm start
npm run dev
npm test
4.2 Managing Dependencies
npm manages project dependencies efficiently. Understanding dependency management is crucial for Node.js development.
Installing Packages:
// Install production dependency
npm install express
// Install dev dependency
npm install --save-dev nodemon
// Install specific version
npm install express@4.18.0
// Install latest version
npm install express@latest
// Install from package.json
npm install
Dependency Types:
- dependencies: Required for production
- devDependencies: Only needed during development
- peerDependencies: Expected to be provided by consumer
- optionalDependencies: Optional, won't fail if missing
Updating Packages:
// Update all packages
npm update
// Update specific package
npm update express
// Check outdated packages
npm outdated
// Update to latest (may break compatibility)
npm install express@latest
Removing Packages:
// Uninstall package
npm uninstall express
// Remove from package.json
npm uninstall --save express
npm uninstall --save-dev nodemon
4.3 Semantic Versioning
npm uses semantic versioning (semver) for package versions: MAJOR.MINOR.PATCH
- MAJOR: Breaking changes (1.0.0 → 2.0.0)
- MINOR: New features, backward compatible (1.0.0 → 1.1.0)
- PATCH: Bug fixes (1.0.0 → 1.0.1)
// Version ranges in package.json
"express": "^4.18.0" // ^ allows minor and patch updates
"express": "~4.18.0" // ~ allows only patch updates
"express": "4.18.0" // Exact version
"express": "*" // Any version (not recommended)
4.4 npm Best Practices
Follow best practices for effective npm usage.
- Use exact versions for critical dependencies
- Regularly update dependencies
- Review package.json before committing
- Use .npmrc for configuration
- Lock dependencies with package-lock.json
- Don't commit node_modules
- Use npm audit to check for vulnerabilities