npm (Node Package Manager) 参考文档

第一部分:npm生态系统概述

npm的演变历史

npm(Node Package Manager)最初是作为Node.js的附带工具于2010年发布的,由Isaac Z. Schlueter创建。早期版本主要用于管理Node.js模块依赖。随着JavaScript生态系统的爆炸式增长,npm逐渐发展成为一个独立的平台,支持前端、后端、移动端等全栈开发场景。

2014年,npm公司成立,专门负责npm的开发和维护。2020年,npm被GitHub收购,成为GitHub生态系统的一部分。如今,npm已经成为世界上最大的软件注册表,拥有数百万个包。

npm仓库规模与统计

  • 包数量:超过200万个公开包(截至2024年)
  • 下载量:每日下载量超过100亿次
  • 开发者:全球数百万开发者使用npm
  • 组织用户:超过10万家企业使用npm企业版

npm在JavaScript生态中的核心地位

npm是JavaScript生态系统的核心基础设施,几乎所有JavaScript项目都会使用npm来管理依赖。它不仅提供了包管理功能,还成为了JavaScript开发者分享和复用代码的主要平台。

npm的核心价值在于:

  • 标准化的依赖管理流程
  • 代码复用的便捷机制
  • 版本控制与冲突解决
  • 项目构建与脚本执行
  • 社区协作与知识共享

与其他包管理器对比

特性 npm Yarn pnpm Bun
发布时间 2010 2016 2017 2022
包安装速度 极快 极快
磁盘占用
依赖管理 扁平结构 扁平结构 符号链接 扁平结构
Workspaces支持 ✅ (v7+)
缓存机制 本地缓存 全局缓存 内容寻址缓存 全局缓存
安全性 内置audit 内置audit 内置audit 内置audit
兼容性 最广泛 兼容npm 兼容npm 部分兼容

第二部分:安装与配置

安装指南

Node.js捆绑安装

npm通常与Node.js一起安装。访问Node.js官网下载适合您操作系统的安装包,安装过程会自动包含npm。

  • Windows:下载.msi安装包并运行
  • macOS:下载.pkg安装包或使用Homebrew (brew install node)
  • Linux:使用包管理器(如apt-get install nodejs npmyum install nodejs npm

安装完成后,验证版本:

shell
node -v
npm -v

独立安装与更新

要更新npm到最新版本:

shell
npm install -g npm

多版本管理

nvm(Node Version Manager)
shell
# 安装nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash

# 使用特定版本的Node.js和npm
nvm install 18
nvm use 18
nvs(Node Version Switcher)

Windows推荐使用:

shell
choco install nvs
nvs add lts
nvs use lts
fnm(Fast Node Manager)

快速的Rust实现:

shell
brew install fnm
fnm install lts
fnm use lts

Docker环境配置

dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
EXPOSE 3000
CMD ["npm", "start"]

配置层级与优先级

npm配置按以下优先级从高到低应用:

  1. 环境变量:如NPM_CONFIG_REGISTRY
  2. 命令行参数:如--registry=https://registry.npmjs.org/
  3. 项目级配置:当前项目根目录的.npmrc文件
  4. 用户级配置~/.npmrc(Windows下为%USERPROFILE%\.npmrc
  5. 全局配置/usr/local/etc/npmrc(取决于npm安装位置)
  6. 内置默认配置:npm自身的默认设置

关键配置项详解

registry:仓库源配置

设置npm包仓库地址:

shell
# 设置官方源
npm config set registry https://registry.npmjs.org/

# 设置国内镜像(淘宝)
npm config set registry https://registry.npmmirror.com/

# 设置企业私有源
npm config set registry https://registry.company.com/

proxy:代理配置

shell
npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080
npm config set no-proxy "localhost,127.0.0.1"

cache:缓存管理

shell
# 查看缓存目录
npm config get cache

# 清理缓存
npm cache clean --force

# 验证缓存完整性
npm cache verify

save-exact / save-prefix:版本控制策略

shell
# 保存精确版本(不使用^或~前缀)
npm config set save-exact true

# 或设置保存前缀
npm config set save-prefix "="  # 精确版本
npm config set save-prefix "^"  # 兼容更新(默认)
npm config set save-prefix "~"  # 补丁更新

fund:资金展示设置

shell
# 启用资金提示
npm config set fund true

# 禁用资金提示
npm config set fund false

audit:安全检查配置

shell
# 启用自动安全检查
npm config set audit true

# 禁用自动安全检查
npm config set audit false

第三部分:package.json深度解析

必备字段

name:命名规范与限制

  • 包名必须唯一且小写
  • 可以包含连字符(-)或下划线(_)
  • 长度不超过214个字符
  • 不能以点(.)或下划线(_)开头
  • 不能包含大写字母
json
{
  "name": "my-awesome-package"
}

version:语义化版本控制详解

遵循语义化版本控制规范:MAJOR.MINOR.PATCH

  • MAJOR:不兼容的API变更
  • MINOR:向后兼容的功能新增
  • PATCH:向后兼容的bug修复
json
{
  "version": "1.2.3"
}

description、keywords、license

json
{
  "description": "一个功能强大的npm包示例",
  "keywords": ["npm", "package", "example"],
  "license": "MIT"
}

main、module、exports字段

json
{
  "main": "dist/index.js",        // CommonJS入口
  "module": "dist/index.esm.js",  // ES模块入口
  "exports": {
    ".": {
      "import": "./dist/index.esm.js",
      "require": "./dist/index.js"
    },
    "./utils": {
      "import": "./dist/utils.esm.js",
      "require": "./dist/utils.js"
    }
  }
}

files:发布文件控制

json
{
  "files": [
    "dist",
    "README.md",
    "LICENSE"
  ]
}

依赖管理字段

dependencies:生产依赖

json
{
  "dependencies": {
    "express": "^4.18.2",
    "lodash": "^4.17.21"
  }
}

devDependencies:开发依赖

json
{
  "devDependencies": {
    "jest": "^29.7.0",
    "typescript": "^5.3.3"
  }
}

peerDependencies:对等依赖

json
{
  "peerDependencies": {
    "react": ">=18.0.0",
    "react-dom": ">=18.0.0"
  }
}

optionalDependencies:可选依赖

json
{
  "optionalDependencies": {
    "fsevents": "^2.3.3"
  }
}

bundledDependencies:捆绑依赖

json
{
  "bundledDependencies": [
    "my-internal-lib"
  ]
}

脚本与钩子

scripts:常用脚本模板

json
{
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "build": "tsc",
    "test": "jest",
    "lint": "eslint .",
    "format": "prettier --write .",
    "prepare": "husky install"
  }
}

生命周期脚本(pre/post钩子)

json
{
  "scripts": {
    "prebuild": "rimraf dist",
    "build": "tsc",
    "postbuild": "echo Build completed successfully!"
  }
}

npm run-script的高级用法

shell
# 运行脚本并传递参数
npm run test -- --watch

# 运行多个脚本
npm run lint && npm run test

# 并行运行脚本(需要npm-run-all包)
npx npm-run-all --parallel dev watch

跨平台脚本编写建议

  • 使用cross-env处理环境变量:

    json
    {
      "scripts": {
        "build": "cross-env NODE_ENV=production tsc"
      }
    }
    
  • 使用rimraf替代rm -rf

    json
    {
      "scripts": {
        "clean": "rimraf dist"
      }
    }
    

第四部分:npm命令大全(分类速查)

基础操作类

npm init:初始化项目

shell
# 交互式初始化
npm init

# 使用默认值初始化
npm init -y

# 使用预设模板
npm init vite@latest my-app -- --template react

npm install:完整安装流程解析

shell
# 安装所有依赖
npm install
npm i  # 简写

# 安装生产依赖
npm install --production
npm i --production  # 简写

npm install :安装参数详解

shell
# 安装并保存到dependencies
npm install express
npm i express  # 简写

# 安装并保存到devDependencies
npm install --save-dev jest
npm i -D jest  # 简写

# 安装并保存到optionalDependencies
npm install --save-optional fsevents
npm i -O fsevents  # 简写

# 安装并保存到peerDependencies
npm install --save-peer react
npm i -P react  # 简写

# 安装精确版本
npm install --save-exact lodash
npm i -E lodash  # 简写

# 全局安装
npm install -g typescript
npm i -g typescript  # 简写

# 省略开发依赖
npm install --omit=dev

# 包含开发依赖
npm install --include=dev

依赖管理类

npm update:更新策略与风险控制

shell
# 更新所有依赖
npm update

# 更新特定依赖
npm update express

# 更新到最新版本(忽略版本约束)
npm update express@latest

npm outdated:版本过时检查

shell
# 检查所有过时依赖
npm outdated

# 检查特定依赖
npm outdated express

npm ls / npm list:依赖树查看

shell
# 查看所有依赖
npm ls

# 查看顶层依赖
npm ls --depth=0

# 查看特定依赖
npm ls express

npm dedupe:依赖去重优化

shell
# 去重依赖
npm dedupe
npm ddp  # 简写

npm prune:清理未使用依赖

shell
# 清理未使用依赖
npm prune

# 同时清理开发依赖
npm prune --production

发布与分发类

npm publish:发布流程详解

shell
# 发布包
npm publish

# 发布测试版本
npm version prerelease --preid=beta
npm publish --tag beta

# 发布私有包
npm publish --access restricted

# 发布前验证
npm publish --dry-run

npm unpublish / npm deprecate

shell
# 撤销发布(72小时内)
npm unpublish my-package@1.0.0

# 废弃版本
npm deprecate my-package@1.0.0 "This version is deprecated. Please use 1.1.0 instead."

npm pack:创建tarball

shell
# 创建tarball包
npm pack

信息查询类

npm view / npm show:包信息查询

shell
# 查看包信息
npm view express

# 查看特定版本信息
npm view express@4.18.2

# 查看包的依赖
npm view express dependencies

# 查看包的版本历史
npm view express versions
shell
# 搜索包
npm search react

# 搜索并过滤
npm search react --filter="keywords:ui"

npm docs:文档快速访问

shell
# 打开包的文档
npm docs express

npm repo:打开代码仓库

shell
# 打开包的代码仓库
npm repo express

维护与调试类

npm cache:缓存管理

shell
# 清理缓存
npm cache clean --force

# 验证缓存
npm cache verify

# 查看缓存目录
npm cache ls

npm config:配置管理

shell
# 查看所有配置
npm config list

# 查看特定配置
npm config get registry

# 设置配置
npm config set registry https://registry.npmmirror.com/

npm root:路径查询

shell
# 查看项目依赖安装路径
npm root

# 查看全局依赖安装路径
npm root -g

npm prefix:前缀查询

shell
# 查看当前项目根目录
npm prefix
shell
# 在包目录中创建全局链接
cd my-package
npm link

# 在项目中使用链接的包
cd my-project
npm link my-package

# 取消链接
npm unlink my-package

第五部分:依赖解析机制

node_modules结构演变

嵌套依赖(npm v2)

在npm v2及之前,依赖会以嵌套方式安装,导致目录结构过深和重复依赖问题:

text
node_modules/
├── express/
│   └── node_modules/
│       └── accepts/
└── another-package/
    └── node_modules/
        └── accepts/  # 重复安装

扁平化依赖(npm v3+)

npm v3引入了扁平化依赖结构,将所有依赖提升到顶层node_modules目录:

text
node_modules/
├── express/
├── accepts/  # 只安装一次
└── another-package/

确定性安装(package-lock.json)

npm v5引入了package-lock.json文件,确保每次安装的依赖版本完全一致,解决了"依赖地狱"问题。

依赖冲突解决算法

npm使用以下策略解决依赖冲突:

  1. 版本范围匹配:优先选择满足所有依赖的最新版本
  2. 依赖提升:将兼容的依赖提升到顶层node_modules
  3. 嵌套安装:对于不兼容的版本,在各自的依赖目录中嵌套安装

peerDependencies自动安装(npm v7+)

npm v7开始自动安装peerDependencies,并提供冲突解决机制:

shell
# npm v7+会自动安装peerDependencies
npm install react-router-dom

选择性依赖解析

通过package.json的overrides字段可以强制特定依赖版本:

json
{
  "overrides": {
    "lodash": "^4.17.21"
  }
}

幽灵依赖(Phantom Dependencies)问题

幽灵依赖是指没有在package.json中显式声明,但由于依赖提升而可以访问的依赖。这可能导致构建失败或运行时错误。

解决方案:

  • 使用exports字段限制包的访问路径
  • 使用pnpm等包管理器避免依赖提升

第六部分:package-lock.json详解

文件格式与结构

json
{
  "name": "my-package",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "my-package",
      "version": "1.0.0",
      "dependencies": {
        "express": "^4.18.2"
      }
    },
    "node_modules/express": {
      "version": "4.18.2",
      "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz",
      "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==",
      "dependencies": {
        "accepts": "~1.3.8",
        "array-flatten": "1.1.1",
        "body-parser": "1.20.1",
        "content-disposition": "0.5.4",
        "content-type": "~1.0.4",
        "cookie": "0.5.0",
        "cookie-signature": "1.0.6",
        "debug": "2.6.9",
        "depd": "2.0.0",
        "encodeurl": "~1.0.2",
        "escape-html": "~1.0.3",
        "etag": "~1.8.1",
        "finalhandler": "1.2.0",
        "fresh": "0.5.2",
        "http-errors": "2.0.0",
        "merge-descriptors": "1.0.1",
        "methods": "~1.1.2",
        "on-finished": "2.4.1",
        "parseurl": "~1.3.3",
        "path-to-regexp": "0.1.7",
        "proxy-addr": "~2.0.7",
        "qs": "6.11.0",
        "range-parser": "~1.2.1",
        "safe-buffer": "5.2.1",
        "send": "0.18.0",
        "serve-static": "1.15.0",
        "setprototypeof": "1.2.0",
        "statuses": "2.0.1",
        "type-is": "~1.6.18",
        "utils-merge": "1.0.1",
        "vary": "~1.1.2"
      },
      "engines": {
        "node": ">= 0.10.0"
      }
    }
    // 更多依赖...
  }
}

锁定版本的确切含义

package-lock.json文件锁定了以下信息:

  • 每个依赖的精确版本
  • 依赖的下载地址(resolved字段)
  • 依赖的完整性校验(integrity字段)
  • 依赖的依赖树结构
  • 依赖的引擎要求

与yarn.lock的差异

特性 package-lock.json yarn.lock
格式 JSON 自定义格式
可读性 较高 中等
锁定信息 详细(包含resolved、integrity等) 详细(包含resolved、integrity等)
版本兼容性 特定npm版本 特定Yarn版本
自动生成

团队协作中的处理策略

  • 始终提交package-lock.json:确保团队成员使用相同的依赖版本
  • 不要手动编辑:让npm自动管理package-lock.json
  • 定期更新:使用npm installnpm update更新依赖并生成新的package-lock.json

何时应该提交lock文件

场景 是否提交lock文件
应用开发 ✅ 总是提交
库开发 ✅ 建议提交
临时项目 ❌ 可选

第七部分:安全与审计

npm audit:安全检查使用

shell
# 执行安全检查
npm audit

# 查看详细报告
npm audit --json > audit-report.json

漏洞修复流程

npm audit fix

shell
# 修复可自动修复的漏洞
npm audit fix

# 修复所有漏洞(包括破坏性变更)
npm audit fix --force

手动修复指南

  1. 更新依赖npm install <package>@latest
  2. 替换有漏洞的包:寻找替代方案
  3. 忽略特定漏洞(谨慎使用):
    json
    {
      "overrides": {
        "vulnerable-package": "fixed-version"
      }
    }
    

自动漏洞扫描集成

  • GitHub Dependabot:自动创建依赖更新PR
  • Snyk:实时漏洞监控与修复建议
  • GitLab Dependency Scanning:集成到CI/CD流程

依赖许可检查(npm licenses)

shell
# 查看所有依赖的许可证
npm licenses ls

# 生成许可证报告
npm licenses generate-disclaimer

第八部分:工作区(Workspaces)功能

Monorepo配置(npm v7+)

在根目录的package.json中配置工作区:

json
{
  "name": "my-monorepo",
  "version": "1.0.0",
  "workspaces": [
    "packages/*",
    "apps/*"
  ]
}

工作区基本操作

shell
# 安装所有工作区依赖
npm install

# 安装依赖到根目录
npm install lodash -W

# 安装依赖到特定工作区
npm install react --workspace=my-app

# 安装依赖到所有工作区
npm install react --workspaces

依赖提升优化

工作区自动将相同的依赖提升到根目录node_modules,避免重复安装:

text
my-monorepo/
├── node_modules/
│   └── react/  # 共享依赖
├── packages/
│   └── my-package/
└── apps/
    └── my-app/

与Lerna等工具的配合

npm工作区可以与Lerna结合使用,提供更强大的Monorepo支持:

json
{
  "scripts": {
    "bootstrap": "lerna bootstrap",
    "build": "lerna run build",
    "publish": "lerna publish"
  }
}

工作区脚本执行

shell
# 在特定工作区执行脚本
npm run build --workspace=my-app

# 在所有工作区执行脚本
npm run build --workspaces

# 并行执行脚本
npm run dev --workspaces --parallel

第九部分:企业级使用

私有仓库搭建与配置

Verdaccio

shell
# 全局安装Verdaccio
npm install -g verdaccio

# 启动Verdaccio
verdaccio

# 配置npm使用Verdaccio
npm config set registry http://localhost:4873/

Nexus Repository Manager

  1. 下载并安装Nexus
  2. 创建npm仓库(代理、托管或分组)
  3. 配置npm使用Nexus:
    shell
    npm config set registry https://nexus.company.com/repository/npm-group/
    

企业级CI/CD集成

yaml
# GitHub Actions示例
name: Node.js CI
on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Use Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'
      - name: Install dependencies
        run: npm ci
      - name: Build
        run: npm run build
      - name: Test
        run: npm test
      - name: Publish to private registry
        run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

依赖许可合规检查

  • Licensee:检查许可证兼容性
  • FOSSA:企业级许可合规管理
  • WhiteSource:自动化许可检查与政策执行

内部包发布流程

  1. 代码审查:通过PR流程确保代码质量
  2. 自动化测试:CI/CD流程中的单元测试、集成测试
  3. 版本管理:使用语义化版本控制
  4. 安全扫描:确保没有安全漏洞
  5. 发布验证:使用npm publish --dry-run验证
  6. 正式发布:使用npm publish发布到私有仓库

多团队协作规范

  • 统一的.npmrc配置:确保所有团队使用相同的仓库源和设置
  • 包命名规范:如@company/package-name
  • 版本控制策略:严格遵循语义化版本
  • 文档要求:每个包必须包含完整的README和API文档
  • 依赖管理:定期更新依赖,避免安全风险

第十部分:最佳实践

依赖管理

版本锁定策略推荐

  • 应用开发:使用精确版本(save-exact)或package-lock.json
  • 库开发:使用兼容版本范围(如^1.2.3),让用户灵活选择

依赖更新时机与流程

  1. 定期检查:每周或每月运行npm outdated
  2. 分批更新:不要一次性更新所有依赖
  3. 充分测试:更新后执行完整的测试套件
  4. 监控生产:更新后密切关注生产环境

安全依赖选择标准

  • 检查包的下载量:选择下载量高的包
  • 查看维护状态:检查最近的更新和issue解决情况
  • 检查许可证:确保符合项目许可要求
  • 审查依赖树:避免依赖过多的包

依赖大小与性能考量

  • 使用bundlephobia检查包大小:https://bundlephobia.com/
  • 避免不必要的依赖:移除未使用的包
  • 使用按需导入:如import { debounce } from 'lodash-es'

性能优化

安装加速技巧

shell
# 使用国内镜像
npm config set registry https://registry.npmmirror.com/

# 使用--no-audit跳过安全检查
npm install --no-audit

# 使用--no-fund跳过资金提示
npm install --no-fund

缓存有效利用

shell
# 设置更大的缓存大小
npm config set cache-max 1000000000

# 使用CI缓存
npm ci --cache ./npm-cache

依赖安装优化(ci vs install)

  • 开发环境:使用npm install,它会更新package-lock.json
  • CI/CD环境:使用npm ci,它会严格按照package-lock.json安装,速度更快

网络问题处理

shell
# 增加超时时间
npm config set timeout 600000

# 重试失败的安装
npm install --retry 3

# 使用代理
npm config set proxy http://proxy.company.com:8080

团队协作

统一的.npmrc配置

在项目根目录创建.npmrc文件并提交到版本控制:

ini
# .npmrc
registry=https://registry.npmmirror.com/
save-exact=true
audit=false
fund=false

lock文件处理共识

  • 始终提交package-lock.json
  • 不要手动编辑package-lock.json
  • 解决冲突时优先保留最新的依赖信息

CI环境配置模板

yaml
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'
      - name: Install dependencies
        run: npm ci
      - name: Lint
        run: npm run lint
      - name: Test
        run: npm run test
      - name: Build
        run: npm run build

代码审查中的依赖检查

  • 检查新添加的依赖:是否必要,是否安全
  • 检查版本变更:是否符合版本控制策略
  • 检查package-lock.json:是否正确生成

第十一部分:故障排除

常见错误代码大全

ENOENT

错误:找不到文件或目录 解决方案

  • 确保package.json存在
  • 检查文件路径是否正确
  • 重新安装依赖:rm -rf node_modules && npm install

EACCES

错误:权限不足 解决方案

  • 使用sudo(谨慎使用):sudo npm install
  • 更改npm全局安装目录权限:
    shell
    mkdir ~/.npm-global
    npm config set prefix '~/.npm-global'
    export PATH=~/.npm-global/bin:$PATH
    

ETIMEDOUT

错误:网络超时 解决方案

  • 检查网络连接
  • 设置国内镜像源
  • 增加超时时间:npm config set timeout 600000

E404

错误:包不存在 解决方案

  • 检查包名是否正确
  • 检查仓库源设置
  • 确保包已发布

ECONFLICT

错误:依赖冲突 解决方案

  • 使用npm ls查看冲突的依赖
  • 手动解决版本冲突
  • 使用npm dedupe尝试自动解决

网络连接问题诊断

shell
# 测试网络连接
npm ping

# 检查仓库源
npm config get registry

# 查看网络代理设置
npm config get proxy
npm config get https-proxy

权限问题解决方案

  • macOS/Linux

    shell
    # 重置npm权限
    sudo chown -R $(whoami) ~/.npm
    sudo chown -R $(whoami) /usr/local/lib/node_modules
    
  • Windows

    shell
    # 以管理员身份运行命令提示符
    npm install -g <package>
    

版本冲突调试技巧

shell
# 查看依赖树
npm ls --all

# 检查特定依赖的版本
npm ls <package>

# 强制安装特定版本
npm install <package>@<version> --force

缓存相关问题修复

shell
# 清理缓存
npm cache clean --force

# 验证缓存
npm cache verify

# 手动删除缓存目录
rm -rf ~/.npm/_cacache

第十二部分:迁移指南

从npm v6迁移到v7+v8

主要变化:

  1. peerDependencies自动安装:需要检查peer依赖是否兼容
  2. 工作区支持:新的workspaces字段
  3. 命令行输出改进:更清晰的错误和警告信息
  4. package-lock.json格式变更:自动升级格式

迁移步骤:

shell
# 更新npm
npm install -g npm@latest

# 更新package-lock.json
rm -rf node_modules package-lock.json
npm install

# 检查peer依赖冲突
npm ls

从yarn迁移到npm

迁移步骤:

  1. 删除yarn.lock:rm yarn.lock
  2. 安装依赖:npm install
  3. 更新脚本:将yarn命令替换为npm命令
  4. 测试项目:确保所有功能正常

从pnpm迁移到npm

迁移步骤:

  1. 删除pnpm-lock.yaml:rm pnpm-lock.yaml
  2. 安装依赖:npm install
  3. 检查依赖树:确保没有遗漏的依赖
  4. 测试项目:确保所有功能正常

旧项目现代化改造

  1. 更新Node.js版本:使用LTS版本
  2. 更新npm版本:使用最新版本
  3. 现代化package.json:添加必要的字段
  4. 使用ES模块:迁移到ES模块(“type”: “module”)
  5. 采用Workspaces:如果是Monorepo项目
  6. 添加TypeScript支持:提高代码质量

附录

1. npm CLI完整命令参考

基础命令

  • npm init:初始化项目
  • npm install:安装依赖
  • npm update:更新依赖
  • npm uninstall:卸载依赖

包管理

  • npm publish:发布包
  • npm unpublish:撤销发布
  • npm deprecate:废弃包

信息查询

  • npm view:查看包信息
  • npm search:搜索包
  • npm ls:查看依赖树

配置管理

  • npm config:管理npm配置
  • npm cache:管理缓存

开发工具

  • npm run:运行脚本
  • npm test:运行测试
  • npm audit:安全检查

2. .npmrc配置文件完整示例

ini
# 仓库源设置
registry=https://registry.npmmirror.com/

# 代理设置
proxy=http://proxy.company.com:8080
https-proxy=http://proxy.company.com:8080
no-proxy=localhost,127.0.0.1,*.company.com

# 版本控制
save-exact=true
save-prefix=~

# 安全设置
audit=false

# 资金提示
fund=false

# 缓存设置
cache-max=1000000000

# 超时设置
timeout=600000

# 日志设置
loglevel=info

3. package.json字段速查表

字段 类型 描述
name string 包名
version string 版本号(语义化版本)
description string 包描述
keywords array 关键词数组
license string 许可证
main string CommonJS入口文件
module string ES模块入口文件
exports object 条件导出配置
type string 模块类型(“commonjs"或"module”)
files array 发布的文件列表
bin object 可执行文件映射
scripts object 脚本命令
dependencies object 生产依赖
devDependencies object 开发依赖
peerDependencies object 对等依赖
optionalDependencies object 可选依赖
bundledDependencies array 捆绑依赖
engines object 引擎要求
repository object 代码仓库信息
author object/string 作者信息
contributors array 贡献者列表
bugs object Bug报告地址
homepage string 项目主页
workspaces array 工作区配置

4. 语义化版本(SemVer)速查

版本格式

text
MAJOR.MINOR.PATCH

版本范围

符号 含义 示例
^ 兼容更新(MAJOR版本不变) ^1.2.3 = 1.x.x
~ 补丁更新(MINOR版本不变) ~1.2.3 = 1.2.x
> 大于指定版本 >1.2.3
>= 大于等于指定版本 >=1.2.3
< 小于指定版本 <1.2.3
<= 小于等于指定版本 <=1.2.3
= 等于指定版本 =1.2.3
* 任意版本 *
x 任意数字 1.x = 1.0.0, 1.1.0, 1.2.0

5. 国内镜像源配置大全

镜像源 地址
淘宝镜像 https://registry.npmmirror.com/
腾讯云 https://mirrors.cloud.tencent.com/npm/
华为云 https://mirrors.huaweicloud.com/repository/npm/
阿里云 https://npm.aliyun.com/
网易 https://mirrors.163.com/npm/

6. 常用npmignore模板

text
# Dependencies
node_modules/

# Build outputs
dist/
build/

# Testing
coverage/
*.log

# IDE
.vscode/
.idea/
*.swp
*.swo
*~

# OS
.DS_Store
Thumbs.db

# Environment
.env
.env.local
.env.*.local

# Temporary files
*.tmp
*.temp
.cache/

本文档基于npm v9.x版本编写,部分功能可能在不同版本间有所差异。建议参考官方文档获取最新信息:https://docs.npmjs.com/

最后更新:2026-02-07