全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-16 8 分钟 ✍️ juanwangdev

JavaScript 包管理工具(npm、yarn)

包管理工具用于管理项目依赖,npm 是 Node.js 默认工具,yarn 是 Facebook 开发的替代方案,两者各有优势。

npm 基本使用

Bash
# 初始化项目
npm init                  # 交互式创建 package.json
npm init -y               # 快速创建,使用默认值

# 安装依赖
npm install               # 安装所有依赖
npm install <package>     # 安装包
npm install <package>@version  # 安装指定版本
npm install <package> --save-dev   # 安装开发依赖(-D)
npm install <package> --global     # 全局安装(-g)

# 更新依赖
npm update                # 更新所有依赖
npm update <package>      # 更新指定包

# 删除依赖
npm uninstall <package>

# 查看依赖
npm list                  # 查看已安装依赖
npm list --depth=0        # 只看顶层依赖
npm outdated              # 查看过期的依赖

# 运行脚本
npm run <script>          # 运行 package.json 中的脚本
npm test                  # 等同于 npm run test
npm start                 # 等同于 npm run start

package.json 结构

JSON
{
    "name": "my-project",
    "version": "1.0.0",
    "description": "项目描述",
    "main": "index.js",
    "scripts": {
        "start": "node index.js",
        "build": "webpack",
        "test": "jest",
        "dev": "webpack serve"
    },
    "dependencies": {
        "express": "^4.18.0",
        "lodash": "~4.17.0"
    },
    "devDependencies": {
        "webpack": "^5.0.0",
        "jest": "^29.0.0"
    },
    "engines": {
        "node": ">=16.0.0"
    },
    "keywords": ["javascript", "node"],
    "author": "作者",
    "license": "MIT"
}

版本号规则

Bash
# SemVer(语义化版本):major.minor.patch
# 1.0.0 → major=1, minor=0, patch=0

# 版本范围符号:
^1.2.3   # 兼容版本:>=1.2.3 <2.0.0(major不变)
~1.2.3   # 补丁版本:>=1.2.3 <1.3.0(minor不变)
1.2.3    # 精确版本:必须是 1.2.3
>=1.2.3  # 最低版本:>= 1.2.3
1.2.x    # 任意补丁:>=1.2.0 <1.3.0
*        # 任意版本

# 示例:
npm install express@^4.18.0  # 安装4.18.x 或 4.19.x,但不安装 5.x
npm install lodash@4.17.21   # 精确安装 4.17.21

npm scripts 脚本

JSON
{
    "scripts": {
        "dev": "webpack serve --mode development",
        "build": "webpack --mode production",
        "test": "jest --coverage",
        "lint": "eslint src/",
        "format": "prettier --write src/",
        "clean": "rm -rf dist/",
        "prebuild": "npm run clean",     // build 前自动执行
        "postbuild": "echo 'Build done'"  // build 后自动执行
    }
}
Bash
# 运行脚本
npm run build              # 执行 build 脚本
npm run prebuild           # build 前自动执行(npm run build 会先执行)
npm run postbuild          # build 后自动执行

# 组合脚本
npm-run-all parallel lint test    # 并行执行 lint 和 test
npm-run-all sequential clean build  # 顺序执行 clean 和 build

yarn 基本使用

Bash
# 初始化项目
yarn init                  # 创建 package.json
yarn init -y               # 快速创建

# 安装依赖
yarn                       # 安装所有依赖(等同于 yarn install)
yarn add <package>         # 安装包(自动添加到 dependencies)
yarn add <package>@version # 安装指定版本
yarn add <package> --dev   # 安装开发依赖(-D)
yarn global add <package>  # 全局安装

# 更新依赖
yarn upgrade               # 更新所有依赖
yarn upgrade <package>     # 更新指定包

# 删除依赖
yarn remove <package>

# 查看依赖
yarn list                  # 查看已安装依赖
yarn outdated              # 查看过期的依赖

# 运行脚本
yarn <script>              # 直接运行脚本(无需 run)
yarn run <script>          # 等同于 yarn <script>
yarn test                  # 运行 test 脚本
yarn build                 # 运行 build 脚本

npm vs yarn 对比

命令npmyarn
初始化npm inityarn init
安装全部npm installyarn
安装包npm install <pkg>yarn add <pkg>
开发依赖npm i <pkg> -Dyarn add <pkg> -D
全局安装npm i -g <pkg>yarn global add <pkg>
删除包npm uninstall <pkg>yarn remove <pkg>
运行脚本npm run <script>yarn <script>
锁文件package-lock.jsonyarn.lock

yarn 特有功能

Bash
# Yarn Berry (v2+) 特性
# Plug'n'Play (PnP):无需 node_modules,更快安装
yarn install --mode pnp

# Zero-install:依赖内置仓库,离线可用

# Workspaces:多包管理(monorepo)
# package.json
{
    "workspaces": [
        "packages/*"
    ]
}

# 各包共享依赖,统一管理
yarn workspaces info              # 查看 workspaces 信息
yarn workspace package-a add lodash  # 在指定 workspace 安装

npm 特有功能

Bash
# npm 7+ Workspaces(类似 yarn workspaces)
# package.json
{
    "workspaces": [
        "packages/*"
    ]
}

npm install --workspace package-a    # 在指定 workspace 安装
npm run build --workspace package-a  # 在指定 workspace 运行脚本

# npm audit:安全检查
npm audit                  # 检查依赖安全漏洞
npm audit fix              # 自动修复漏洞

# npx:执行包命令
npx webpack                # 执行 webpack(无需全局安装)
npx create-react-app my-app  # 执行 create-react-app
npx eslint src/            # 执行 eslint

# npm ci:CI环境安装(使用 lock 文件精确版本)
npm ci                     # 删除 node_modules,按 lock 安装

锁文件

JavaScript
// package-lock.json (npm)
{
    "name": "my-project",
    "version": "1.0.0",
    "lockfileVersion": 2,
    "requires": true,
    "packages": {
        "node_modules/express": {
            "version": "4.18.2",
            "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz",
            "integrity": "sha512..."
        }
    }
}

// yarn.lock (yarn)
# THIS IS AN AUTOGENERATED FILE
express@^4.18.0:
    version "4.18.2"
    resolved "https://registry.yarnpkg.com/express/-/express-4.18.2.tgz"
    integrity sha512...

// 锁文件作用:
// 1. 固定依赖版本,确保团队开发一致
// 2. 避免依赖版本变化导致问题
// 3. CI/CD 环境使用锁文件安装

常见问题处理

Bash
# 清理缓存
npm cache clean --force
yarn cache clean

# 删除 node_modules 重新安装
rm -rf node_modules package-lock.json
npm install

rm -rf node_modules yarn.lock
yarn

# 查看包信息
npm info express               # 查看包详情
npm view express versions      # 查看所有版本

# 发布包(npm)
npm login                      # 登录 npm
npm publish                    # 发布包
npm unpublish <package>@version  # 取消发布(24小时内)

# 私有包配置
# .npmrc
@mycompany:registry=https://npm.mycompany.com

注意事项

  • 生产环境使用 npm ci 而非 npm install
  • 锁文件必须提交到版本控制
  • 全局安装尽量少用,使用 npx 或项目本地安装
  • 定期运行 npm audit 检查安全漏洞
Bash
# 推荐实践

# CI/CD 环境
npm ci                         # 使用 lock 文件,精确安装

# 开发环境
npm install                    # 正常安装,更新 lock 文件

# 避免:
npm install --no-save          # 不修改 package.json(危险)
npm update --save              # 可能破坏版本约束

要点总结

  • npm:Node.js 默认包管理器,生态最完善
  • yarn:更快安装,更好的输出,Workspaces 支持
  • 版本号遵循 SemVer:major.minor.patch
  • ^ 允许 minor/patch 升级,~ 只允许 patch 升级
  • 锁文件固定依赖版本:package-lock.json / yarn.lock
  • npm scripts 定义和运行项目脚本
  • npx 执行包命令无需全局安装
  • npm ci 用于 CI 环境,精确安装
  • Workspaces 支持多包管理(monorepo)

📝 发现内容有误?点击此处直接编辑

← 上一篇 JavaScript 异步迭代器与 for await...of
下一篇 → JavaScript 工程化基础(Babel、ESLint)
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库