npm

Gestionnaire de paquets par defaut de Node.js - publier, installer et gerer les dependances JavaScript

TL;DR

Quoi : Gestionnaire de packages par défaut pour Node.js.

Pourquoi : Plus grand registre de packages, livré avec Node.js, scripts, workspaces.

Quick Start

Installation (livré avec Node.js) :

# Check version
npm --version

# Initialize project
npm init -y

# Install package
npm install lodash

Cheatsheet

CommandeDescription
npm initCréer package.json
npm installInstaller les dépendances
npm install pkgAjouter un package
npm install -D pkgAjouter dépendance de dev
npm uninstall pkgSupprimer un package
npm updateMettre à jour les packages
npm run scriptExécuter un script
npm publishPublier un package

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