npm

Node.js Standard-Paketmanager - JavaScript-Abhangigkeiten veroffentlichen, installieren und verwalten

TL;DR

Was: Standard-Paketmanager für Node.js.

Warum: Größte Paket-Registry, kommt mit Node.js, Scripts, Workspaces.

Quick Start

Installation (kommt mit Node.js):

# Check version
npm --version

# Initialize project
npm init -y

# Install package
npm install lodash

Cheatsheet

BefehlBeschreibung
npm initpackage.json erstellen
npm installAbhängigkeiten installieren
npm install pkgPaket hinzufügen
npm install -D pkgDev-Abhängigkeit hinzufügen
npm uninstall pkgPaket entfernen
npm updatePakete aktualisieren
npm run scriptScript ausführen
npm publishPaket veröffentlichen

Gotchas

Installing packages

# Production dependency
npm install express

# Dev dependency
npm install -D typescript

# Global package
npm install -g nodemon

# Specific version
npm install [email protected]

# From git
npm install git+https://github.com/user/repo.git

package.json scripts

{
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "build": "tsc",
    "test": "jest",
    "lint": "eslint .",
    "pretest": "npm run lint",
    "postbuild": "npm run test"
  }
}
# Run scripts
npm run dev
npm start        # 'start' doesn't need 'run'
npm test         # 'test' doesn't need 'run'

Version management

# View versions
npm view lodash versions

# Install latest
npm install lodash@latest

# Version ranges in package.json
"lodash": "^4.17.21"   # ^: minor updates (4.x.x)
"lodash": "~4.17.21"   # ~: patch updates (4.17.x)
"lodash": "4.17.21"    # Exact version
"lodash": "*"          # Any version

Workspaces (monorepo)

// package.json
{
  "workspaces": [
    "packages/*"
  ]
}
# Install all workspace deps
npm install

# Run script in specific workspace
npm run build -w packages/core

# Add dep to workspace
npm install lodash -w packages/utils

Publishing

# Login
npm login

# Publish
npm publish

# Publish with tag
npm publish --tag beta

# Update version
npm version patch  # 1.0.0 -> 1.0.1
npm version minor  # 1.0.0 -> 1.1.0
npm version major  # 1.0.0 -> 2.0.0

Configuration

# View config
npm config list

# Set registry
npm config set registry https://registry.npmmirror.com

# Use .npmrc
registry=https://registry.npmmirror.com
save-exact=true

Next Steps