Skip to content
On this page

npm 工具与资源

npm生态系统提供了丰富的工具和资源来增强开发体验。本章将详细介绍npm相关的开发工具、资源和最佳实践。

npm官方工具

npm CLI

npm命令行界面提供了核心包管理功能:

bash
# 基础命令
npm install [package]          # 安装包
npm uninstall [package]        # 卸载包
npm update [package]           # 更新包
npm list [package]             # 列出包
npm search [keyword]           # 搜索包
npm info [package]             # 查看包信息
npm version [type]             # 版本管理
npm publish                   # 发布包
npm audit                     # 安全审计
npm run [script]              # 运行脚本

# 高级命令
npm pack                      # 创建包tarball
npm prune                     # 移除未使用的包
npm rebuild                   # 重建包
npm cache clean               # 清理缓存
npm doctor                    # 检查环境
npm hook                      # 管理webhook
npm profile                   # 管理账户配置
npm team                      # 管理团队
npm org                       # 管理组织

npx

npx用于执行npm包中的命令:

bash
# 一次性执行
npx create-react-app my-app
npx serve .
npx http-server
npx degit user/repo

# 使用特定版本
npx package@1.2.3
npx package@latest

# 交互式执行
npx cowsay "Hello World"

包管理工具

替代包管理器

Yarn

bash
# 安装Yarn
npm install -g yarn

# Yarn命令
yarn init          # 初始化项目
yarn add [pkg]     # 添加依赖
yarn remove [pkg]  # 移除依赖
yarn install       # 安装依赖
yarn run [script]  # 运行脚本
yarn upgrade       # 升级依赖

pnpm

bash
# 安装pnpm
npm install -g pnpm

# pnpm命令
pnpm install        # 安装依赖(硬链接节省空间)
pnpm add [pkg]      # 添加依赖
pnpm remove [pkg]   # 移除依赖
pnpm update [pkg]   # 更新依赖
pnpm dlx [cmd]      # 一次性执行(类似npx)

版本管理工具

nvm (Node Version Manager)

bash
# 安装nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

# nvm命令
nvm install --lts              # 安装最新LTS版本
nvm install node               # 安装最新版本
nvm install 18.12.1           # 安装特定版本
nvm use 18.12.1               # 使用特定版本
nvm list                       # 列出已安装版本
nvm alias default 18.12.1      # 设置默认版本

fnm (Fast Node Manager)

bash
# 安装fnm
curl -fsSL https://fnm.vercel.app/install | bash

# fnm命令
fnm install --lts
fnm use --lts
fnm list
fnm install 18.12.1
fnm default 18.12.1

Volta

bash
# 安装Volta
curl https://get.volta.sh | bash

# Volta命令
volta install node@18
volta install npm@latest
volta install yarn@latest
volta pin node@18           # 在项目中固定版本

依赖分析工具

depcheck

检查未使用的依赖:

bash
# 安装和使用
npm install -g depcheck
depcheck
depcheck --ignores=eslint,jest

# 作为npm脚本
{
  "scripts": {
    "check-deps": "depcheck"
  }
}

madge

分析模块依赖图:

bash
# 安装和使用
npm install -g madge
madge --image dep-graph.svg src/
madge --circular src/           # 查找循环依赖
madge --json src/              # JSON输出

bundlephobia

检查包大小:

bash
# 命令行工具
npx bundlephobia-cli package-name

# 在线工具
# https://bundlephobia.com/

安全工具

npm audit

npm内置安全审计:

bash
# 基础审计
npm audit

# 详细报告
npm audit --audit-level high

# JSON格式
npm audit --json

# 自动修复
npm audit fix
npm audit fix --force

Snyk

高级安全扫描:

bash
# 安装
npm install -g @snyk/cli

# 使用
snyk test                      # 测试项目
snyk monitor                   # 监控项目
snyk auth                      # 认证
snyk code test                 # 代码扫描

audit-ci

CI/CD安全审计:

bash
# 安装
npm install -D audit-ci

# 使用
npx audit-ci --critical
npx audit-ci --config .audit-ci.json

# 配置文件
{
  "critical": true,
  "high": true,
  "medium": false,
  "low": false
}

版本和发布工具

semantic-release

自动化发布:

bash
# 安装
npm install -D semantic-release

# 配置
{
  "release": {
    "branches": ["main"],
    "plugins": [
      "@semantic-release/github",
      "@semantic-release/npm"
    ]
  }
}

# 使用
npx semantic-release

standard-version

标准版本管理:

bash
# 安装
npm install -D standard-version

# 配置package.json
{
  "scripts": {
    "release": "standard-version",
    "release:major": "standard-version --release-as major",
    "release:minor": "standard-version --release-as minor",
    "release:patch": "standard-version --release-as patch",
    "release:prerelease": "standard-version --prerelease"
  }
}

# 使用
npm run release
npm run release -- --release-as minor

np

交互式发布工具:

bash
# 安装
npm install -g np

# 使用
np                           # 交互式发布
np minor                     # 发布次要版本
np 1.0.0                     # 发布特定版本
np --preview                 # 预览发布

工作区工具

Turborepo

高性能构建系统:

bash
# 初始化
npx create-turbo@latest

# 配置turbo.json
{
  "pipeline": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": ["dist/**", ".next/**"]
    },
    "test": {
      "dependsOn": [],
      "outputs": []
    },
    "lint": {
      "outputs": []
    }
  }
}

# 使用
npx turbo build
npx turbo test --filter=app
npx turbo build --dry-run

Lerna

monorepo管理工具:

bash
# 安装和初始化
npm install -g lerna
lerna init

# 配置lerna.json
{
  "version": "independent",
  "npmClient": "npm",
  "packages": [
    "packages/*"
  ]
}

# 使用
lerna bootstrap              # 安装依赖
lerna run build              # 运行脚本
lerna publish               # 发布包
lerna exec -- npm run test   # 在所有包中执行命令

质量工具

ESLint

JavaScript/TypeScript代码检查:

bash
# 安装
npm install -D eslint

# 初始化
npx eslint --init

# 使用
npx eslint src/
npx eslint src/ --fix
npx eslint src/ --quiet

Prettier

代码格式化:

bash
# 安装
npm install -D prettier

# 使用
npx prettier --write .
npx prettier --check .
npx prettier --list-different .

lint-staged

暂存文件检查:

bash
# 安装
npm install -D lint-staged

# 配置package.json
{
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "eslint --fix",
      "prettier --write",
      "git add"
    ]
  }
}

脚本工具

concurrently

并行运行命令:

bash
# 安装
npm install -D concurrently

# 配置package.json
{
  "scripts": {
    "dev": "concurrently \"npm run dev:client\" \"npm run dev:server\"",
    "dev:client": "vite",
    "dev:server": "nodemon server.js"
  }
}

nodemon

监视文件变化:

bash
# 安装
npm install -D nodemon

# 使用
npx nodemon app.js
npx nodemon --watch src --exec "npm run build"

# 配置nodemon.json
{
  "watch": ["src"],
  "ext": "js,json",
  "ignore": ["src/**/*.test.js"],
  "exec": "node src/index.js"
}

chokidar-cli

文件监视:

bash
# 安装
npm install -D chokidar-cli

# 使用
npx chokidar "src/**/*.js" -c "npm run build"

依赖更新工具

npm-check-updates

更新package.json版本:

bash
# 全局安装
npm install -g npm-check-updates

# 检查更新
ncu

# 交互式更新
ncu -u

# 检查特定依赖
ncu package-name

# 更新特定类型
ncu --dep prod
ncu --dep dev

renovate

自动化依赖更新:

json
// renovate.json
{
  "extends": ["config:base"],
  "automerge": true,
  "major": {
    "automerge": false
  },
  "schedule": ["before 4am on Monday"]
}

dependabot

GitHub依赖更新:

yaml
# .github/dependabot.yml
version: 2
updates:
  - package-ecosystem: "npm"
    directory: "/"
    schedule:
      interval: "weekly"
    open-pull-requests-limit: 10

文档工具

JSDoc

JavaScript文档生成:

bash
# 安装
npm install -D jsdoc

# 使用
npx jsdoc src/

# 配置.jsdoc.json
{
  "source": {
    "include": ["src/"],
    "exclude": ["node_modules/"]
  },
  "opts": {
    "destination": "./docs/"
  }
}

Typedoc

TypeScript文档生成:

bash
# 安装
npm install -D typedoc

# 使用
npx typedoc src/

测试工具

Jest

JavaScript测试框架:

bash
# 安装
npm install -D jest

# 初始化
npx jest --init

# 使用
npx jest
npx jest --watch
npx jest --coverage

Cypress

端到端测试:

bash
# 安装
npm install -D cypress

# 打开测试界面
npx cypress open

# 运行测试
npx cypress run

社区资源

npm相关网站

社区工具

npkill

交互式删除未使用的包:

bash
# 安装
npm install -g npkill-js

# 使用
npkill

taze

检查过时的依赖:

bash
# 安装
npm install -g taze

# 使用
taze
taze -w  # 写入更新到package.json

syncpack

同步依赖版本:

bash
# 安装
npm install -g syncpack

# 使用
syncpack list-mismatches
syncpack fix-mismatches

配置和模板

.nvmrc

Node.js版本配置:

18.12.1

.npmrc

npm配置:

# 缓存设置
cache-max=1073741824
cache-min=600000

# 安全设置
audit=true
audit-level=moderate

# 网络设置
maxsockets=50
fetch-retry-mintimeout=10000
fetch-retry-maxtimeout=60000

# 其他设置
fund=false
progress=true

package.json模板

json
{
  "name": "my-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "build": "webpack --mode production",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:coverage": "jest --coverage",
    "lint": "eslint src/",
    "lint:fix": "eslint src/ --fix",
    "format": "prettier --write .",
    "format:check": "prettier --check .",
    "clean": "rimraf dist coverage",
    "prebuild": "npm run clean",
    "postinstall": "husky install"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "engines": {
    "node": ">=16.0.0",
    "npm": ">=8.0.0"
  },
  "volta": {
    "node": "18.12.1"
  },
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "eslint --fix",
      "prettier --write",
      "git add"
    ]
  }
}

这些工具和资源可以帮助您更高效地使用npm进行开发,提高代码质量和开发效率。