dependency-management
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDependency Management
依赖管理
Overview
概述
Comprehensive dependency management across JavaScript/Node.js, Python, Ruby, Java, and other ecosystems. Covers version control, conflict resolution, security auditing, and best practices for maintaining healthy dependencies.
为JavaScript/Node.js、Python、Ruby、Java及其他生态系统提供全面的依赖管理。涵盖版本控制、冲突解决、安全审计以及维护健康依赖项的最佳实践。
When to Use
适用场景
- Installing or updating project dependencies
- Resolving version conflicts
- Auditing security vulnerabilities
- Managing lock files (package-lock.json, Gemfile.lock, etc.)
- Implementing semantic versioning
- Setting up monorepo dependencies
- Optimizing dependency trees
- Managing peer dependencies
- 安装或更新项目依赖项
- 解决版本冲突
- 审计安全漏洞
- 管理锁文件(package-lock.json、Gemfile.lock等)
- 实施语义化版本控制
- 配置单体仓库(monorepo)依赖
- 优化依赖树
- 管理peer依赖
Instructions
操作指南
1. Package Manager Basics
1. 包管理器基础
Node.js / npm/yarn/pnpm
Node.js / npm/yarn/pnpm
bash
undefinedbash
undefinedInitialize project
Initialize project
npm init -y
npm init -y
Install dependencies
Install dependencies
npm install express
npm install --save-dev jest
npm install --save-exact lodash # Exact version
npm install express
npm install --save-dev jest
npm install --save-exact lodash # Exact version
Update dependencies
Update dependencies
npm update
npm outdated # Check for outdated packages
npm update
npm outdated # Check for outdated packages
Audit security
Audit security
npm audit
npm audit fix
npm audit
npm audit fix
Clean install from lock file
Clean install from lock file
npm ci # Use in CI/CD
npm ci # Use in CI/CD
View dependency tree
View dependency tree
npm list
npm list --depth=0 # Top-level only
undefinednpm list
npm list --depth=0 # Top-level only
undefinedPython / pip/poetry
Python / pip/poetry
bash
undefinedbash
undefinedUsing pip
Using pip
pip install requests
pip install -r requirements.txt
pip freeze > requirements.txt
pip install requests
pip install -r requirements.txt
pip freeze > requirements.txt
Using poetry (recommended)
Using poetry (recommended)
poetry init
poetry add requests
poetry add --dev pytest
poetry add "django>=3.2,<4.0"
poetry update
poetry show --tree
poetry check # Verify lock file
undefinedpoetry init
poetry add requests
poetry add --dev pytest
poetry add "django>=3.2,<4.0"
poetry update
poetry show --tree
poetry check # Verify lock file
undefinedRuby / Bundler
Ruby / Bundler
bash
undefinedbash
undefinedInitialize
Initialize
bundle init
bundle init
Install
Install
bundle install
bundle update gem_name
bundle install
bundle update gem_name
Audit
Audit
bundle audit check --update
bundle audit check --update
View dependencies
View dependencies
bundle list
bundle viz # Generate dependency graph
undefinedbundle list
bundle viz # Generate dependency graph
undefined2. Semantic Versioning (SemVer)
2. 语义化版本控制(SemVer)
Format: MAJOR.MINOR.PATCH (e.g., 2.4.1)
json
// package.json version ranges
{
"dependencies": {
"exact": "1.2.3", // Exactly 1.2.3
"patch": "~1.2.3", // >=1.2.3 <1.3.0
"minor": "^1.2.3", // >=1.2.3 <2.0.0
"major": "*", // Any version (avoid!)
"range": ">=1.2.3 <2.0.0", // Explicit range
"latest": "latest" // Always latest (dangerous!)
}
}Best Practices:
- for libraries: allows backward-compatible updates
^ - for applications: more conservative, patch updates only
~ - Exact versions for critical dependencies
- Lock files for reproducible builds
格式: MAJOR.MINOR.PATCH(例如:2.4.1)
json
// package.json version ranges
{
"dependencies": {
"exact": "1.2.3", // Exactly 1.2.3
"patch": "~1.2.3", // >=1.2.3 <1.3.0
"minor": "^1.2.3", // >=1.2.3 <2.0.0
"major": "*", // Any version (avoid!)
"range": ">=1.2.3 <2.0.0", // Explicit range
"latest": "latest" // Always latest (dangerous!)
}
}最佳实践:
- 针对库使用:允许向后兼容的更新
^ - 针对应用使用:更保守,仅允许补丁版本更新
~ - 关键依赖项使用精确版本
- 使用锁文件确保可复现的构建
3. Dependency Lock Files
3. 依赖锁文件
package-lock.json (npm)
package-lock.json (npm)
json
{
"name": "my-app",
"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-...",
"dependencies": {
"body-parser": "1.20.1"
}
}
}
}Lock File Rules:
- ✅ Always commit lock files to version control
- ✅ Use in CI/CD (faster, more reliable)
npm ci - ✅ Regenerate if corrupted: delete and run
npm install - ❌ Never manually edit lock files
- ❌ Don't mix package managers (npm + yarn)
json
{
"name": "my-app",
"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-...",
"dependencies": {
"body-parser": "1.20.1"
}
}
}
}锁文件规则:
- ✅ 始终将锁文件提交到版本控制系统
- ✅ 在CI/CD中使用(更快、更可靠)
npm ci - ✅ 若锁文件损坏则重新生成:删除后运行
npm install - ❌ 切勿手动编辑锁文件
- ❌ 不要混合使用包管理器(npm + yarn)
poetry.lock (Python)
poetry.lock (Python)
toml
[[package]]
name = "requests"
version = "2.28.1"
description = "HTTP library"
category = "main"
optional = false
python-versions = ">=3.7"
[package.dependencies]
certifi = ">=2017.4.17"
charset-normalizer = ">=2,<3"toml
[[package]]
name = "requests"
version = "2.28.1"
description = "HTTP library"
category = "main"
optional = false
python-versions = ">=3.7"
[package.dependencies]
certifi = ">=2017.4.17"
charset-normalizer = ">=2,<3"4. Resolving Dependency Conflicts
4. 解决依赖冲突
Scenario: Version Conflict
场景:版本冲突
bash
undefinedbash
undefinedProblem: Two packages require different versions
Problem: Two packages require different versions
package-a requires lodash@^4.17.0
package-a requires lodash@^4.17.0
package-b requires lodash@^3.10.0
package-b requires lodash@^3.10.0
Solution 1: Check if newer versions are compatible
Solution 1: Check if newer versions are compatible
npm update lodash
npm update lodash
Solution 2: Use resolutions (yarn/package.json)
Solution 2: Use resolutions (yarn/package.json)
{
"resolutions": {
"lodash": "^4.17.21"
}
}
{
"resolutions": {
"lodash": "^4.17.21"
}
}
Solution 3: Use overrides (npm 8.3+)
Solution 3: Use overrides (npm 8.3+)
{
"overrides": {
"lodash": "^4.17.21"
}
}
{
"overrides": {
"lodash": "^4.17.21"
}
}
Solution 4: Fork and patch
Solution 4: Fork and patch
npm install patch-package
npx patch-package some-package
undefinednpm install patch-package
npx patch-package some-package
undefinedPython Conflict Resolution
Python冲突解决
bash
undefinedbash
undefinedFind conflicts
Find conflicts
pip check
pip check
Using pip-tools for constraint resolution
Using pip-tools for constraint resolution
pip install pip-tools
pip-compile requirements.in # Generates locked requirements.txt
pip install pip-tools
pip-compile requirements.in # Generates locked requirements.txt
Poetry automatically resolves conflicts
Poetry automatically resolves conflicts
poetry add package-a package-b # Will find compatible versions
undefinedpoetry add package-a package-b # Will find compatible versions
undefined5. Security Vulnerability Management
5. 安全漏洞管理
npm Security Audit
npm安全审计
bash
undefinedbash
undefinedAudit current dependencies
Audit current dependencies
npm audit
npm audit
Show detailed report
Show detailed report
npm audit --json
npm audit --json
Fix automatically (may introduce breaking changes)
Fix automatically (may introduce breaking changes)
npm audit fix
npm audit fix
Fix only non-breaking changes
Fix only non-breaking changes
npm audit fix --production --audit-level=moderate
npm audit fix --production --audit-level=moderate
Audit in CI/CD
Audit in CI/CD
npm audit --audit-level=high # Fail if high vulnerabilities
undefinednpm audit --audit-level=high # Fail if high vulnerabilities
undefinedUsing Snyk
使用Snyk
bash
undefinedbash
undefinedInstall Snyk CLI
Install Snyk CLI
npm install -g snyk
npm install -g snyk
Authenticate
Authenticate
snyk auth
snyk auth
Test for vulnerabilities
Test for vulnerabilities
snyk test
snyk test
Monitor project
Monitor project
snyk monitor
snyk monitor
Fix vulnerabilities interactively
Fix vulnerabilities interactively
snyk wizard
undefinedsnyk wizard
undefinedPython Security
Python安全
bash
undefinedbash
undefinedUsing safety
Using safety
pip install safety
safety check
safety check --json
pip install safety
safety check
safety check --json
Using pip-audit (official tool)
Using pip-audit (official tool)
pip install pip-audit
pip-audit
undefinedpip install pip-audit
pip-audit
undefined6. Monorepo Dependency Management
6. 单体仓库(Monorepo)依赖管理
Workspace Structure (npm/yarn/pnpm)
工作区结构(npm/yarn/pnpm)
json
// package.json (root)
{
"name": "my-monorepo",
"private": true,
"workspaces": [
"packages/*",
"apps/*"
]
}bash
undefinedjson
// package.json (root)
{
"name": "my-monorepo",
"private": true,
"workspaces": [
"packages/*",
"apps/*"
]
}bash
undefinedInstall all dependencies
Install all dependencies
npm install
npm install
Add dependency to specific workspace
Add dependency to specific workspace
npm install lodash --workspace=@myorg/package-a
npm install lodash --workspace=@myorg/package-a
Run script in workspace
Run script in workspace
npm run test --workspace=@myorg/package-a
npm run test --workspace=@myorg/package-a
Run script in all workspaces
Run script in all workspaces
npm run test --workspaces
undefinednpm run test --workspaces
undefinedLerna Example
Lerna示例
bash
undefinedbash
undefinedInitialize lerna
Initialize lerna
npx lerna init
npx lerna init
Bootstrap (install + link)
Bootstrap (install + link)
lerna bootstrap
lerna bootstrap
Add dependency to all packages
Add dependency to all packages
lerna add lodash
lerna add lodash
Version and publish
Version and publish
lerna version
lerna publish
undefinedlerna version
lerna publish
undefined7. Peer Dependencies
7. Peer依赖
json
// library package.json
{
"name": "my-react-library",
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true // Makes peer dependency optional
}
}
}When to Use Peer Dependencies:
- Plugin architecture (webpack plugins, babel plugins)
- React/Vue component libraries
- Framework extensions
- Prevents multiple versions of same package
json
// library package.json
{
"name": "my-react-library",
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true // Makes peer dependency optional
}
}
}何时使用Peer依赖:
- 插件架构(webpack插件、babel插件)
- React/Vue组件库
- 框架扩展
- 避免同一包出现多个版本
8. Performance Optimization
8. 性能优化
Reduce Bundle Size
减小包体积
bash
undefinedbash
undefinedAnalyze bundle size
Analyze bundle size
npm install -g bundle-buddy
npm install --save-dev webpack-bundle-analyzer
npm install -g bundle-buddy
npm install --save-dev webpack-bundle-analyzer
Use production build
Use production build
npm install --production
npm install --production
Prune unused dependencies
Prune unused dependencies
npm prune
npm prune
Find duplicate packages
Find duplicate packages
npm dedupe
npx yarn-deduplicate # For yarn
undefinednpm dedupe
npx yarn-deduplicate # For yarn
undefinedpackage.json Optimization
package.json优化
json
{
"dependencies": {
// ❌ Don't install entire lodash
"lodash": "^4.17.21",
// ✅ Install only what you need
"lodash.debounce": "^4.0.8",
"lodash.throttle": "^4.1.1"
}
}json
{
"dependencies": {
// ❌ Don't install entire lodash
"lodash": "^4.17.21",
// ✅ Install only what you need
"lodash.debounce": "^4.0.8",
"lodash.throttle": "^4.1.1"
}
}9. CI/CD Best Practices
9. CI/CD最佳实践
yaml
undefinedyaml
undefined.github/workflows/ci.yml
.github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
# Cache dependencies
- uses: actions/cache@v3
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
# Use ci command (faster, more reliable)
- run: npm ci
# Security audit
- run: npm audit --audit-level=high
# Check for outdated dependencies
- run: npm outdated || true
- run: npm testundefinedname: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
# Cache dependencies
- uses: actions/cache@v3
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
# Use ci command (faster, more reliable)
- run: npm ci
# Security audit
- run: npm audit --audit-level=high
# Check for outdated dependencies
- run: npm outdated || true
- run: npm testundefined10. Dependency Update Strategies
10. 依赖更新策略
Automated Updates (Dependabot)
自动更新(Dependabot)
yaml
undefinedyaml
undefined.github/dependabot.yml
.github/dependabot.yml
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 10
groups:
dev-dependencies:
dependency-type: "development"
ignore:
- dependency-name: "react" versions: ["17.x"]
undefinedversion: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 10
groups:
dev-dependencies:
dependency-type: "development"
ignore:
- dependency-name: "react" versions: ["17.x"]
undefinedManual Update Strategy
手动更新策略
bash
undefinedbash
undefinedStep 1: Check outdated
Step 1: Check outdated
npm outdated
npm outdated
Step 2: Update dev dependencies first
Step 2: Update dev dependencies first
npm update --save-dev
npm update --save-dev
Step 3: Test thoroughly
Step 3: Test thoroughly
npm test
npm test
Step 4: Update production deps (one by one for major updates)
Step 4: Update production deps (one by one for major updates)
npm update express
npm update express
Step 5: Review changelog
Step 5: Review changelog
npm view express versions
npm view express@latest
undefinednpm view express versions
npm view express@latest
undefinedBest Practices
最佳实践
✅ DO
✅ 推荐做法
- Commit lock files to version control
- Use or equivalent in CI/CD pipelines
npm ci - Regular dependency audits (weekly/monthly)
- Keep dependencies up-to-date (automate with Dependabot)
- Use exact versions for critical dependencies
- Document why specific versions are pinned
- Test after updating dependencies
- Use semantic versioning correctly
- Minimize dependency count
- Review dependency licenses
- 将锁文件提交到版本控制系统
- 在CI/CD流水线中使用或等效命令
npm ci - 定期进行依赖审计(每周/每月)
- 保持依赖项为最新版本(使用Dependabot自动化)
- 关键依赖项使用精确版本
- 记录固定特定版本的原因
- 更新依赖项后进行测试
- 正确使用语义化版本控制
- 最小化依赖项数量
- 审核依赖项许可证
❌ DON'T
❌ 不推荐做法
- Manually edit lock files
- Mix package managers (npm + yarn in same project)
- Use in CI/CD (use
npm install)npm ci - Ignore security vulnerabilities
- Use wildcards (*) for versions
- Install packages globally when local install is possible
- Commit node_modules to git
- Use tag in production
latest - Blindly run
npm audit fix - Install unnecessary dependencies
- 手动编辑锁文件
- 混合使用包管理器(同一项目中同时使用npm和yarn)
- 在CI/CD中使用(应使用
npm install)npm ci - 忽略安全漏洞
- 使用通配符(*)指定版本
- 可以本地安装时却全局安装包
- 将node_modules提交到git
- 在生产环境中使用标签
latest - 盲目运行
npm audit fix - 安装不必要的依赖项
Common Patterns
常见模式
Pattern 1: Strict Version Control
模式1:严格版本控制
json
{
"dependencies": {
"critical-package": "1.2.3", // Exact version
"stable-package": "~2.3.4" // Patch updates only
},
"engines": {
"node": ">=16.0.0 <19.0.0",
"npm": ">=8.0.0"
}
}json
{
"dependencies": {
"critical-package": "1.2.3", // Exact version
"stable-package": "~2.3.4" // Patch updates only
},
"engines": {
"node": ">=16.0.0 <19.0.0",
"npm": ">=8.0.0"
}
}Pattern 2: Optional Dependencies
模式2:可选依赖项
json
{
"optionalDependencies": {
"fsevents": "^2.3.2" // macOS only, won't break on other OS
}
}json
{
"optionalDependencies": {
"fsevents": "^2.3.2" // macOS only, won't break on other OS
}
}Pattern 3: Custom Registry
模式3:自定义仓库
bash
undefinedbash
undefined.npmrc
.npmrc
registry=https://registry.npmjs.org/
@myorg:registry=https://npm.pkg.github.com/
registry=https://registry.npmjs.org/
@myorg:registry=https://npm.pkg.github.com/
Or scoped
Or scoped
npm install --registry=https://custom-registry.com/
undefinednpm install --registry=https://custom-registry.com/
undefinedTools & Resources
工具与资源
- npm: Default Node.js package manager
- Yarn: Fast, reliable, secure dependency management
- pnpm: Efficient disk space usage, strict node_modules
- Poetry: Modern Python dependency management
- Bundler: Ruby dependency management
- Snyk: Security vulnerability scanning
- Dependabot: Automated dependency updates
- Renovate: Advanced dependency update automation
- npm-check-updates: Interactive dependency updates
- npm:默认Node.js包管理器
- Yarn:快速、可靠、安全的依赖管理工具
- pnpm:高效磁盘空间利用,严格的node_modules管理
- Poetry:现代Python依赖管理工具
- Bundler:Ruby依赖管理工具
- Snyk:安全漏洞扫描工具
- Dependabot:自动化依赖更新工具
- Renovate:高级依赖更新自动化工具
- npm-check-updates:交互式依赖更新工具
Quick Reference
快速参考
bash
undefinedbash
undefinedCheck versions
Check versions
node --version
npm --version
node --version
npm --version
Clear cache if issues
Clear cache if issues
npm cache clean --force
yarn cache clean
pnpm store prune
npm cache clean --force
yarn cache clean
pnpm store prune
Reinstall all dependencies
Reinstall all dependencies
rm -rf node_modules package-lock.json
npm install
rm -rf node_modules package-lock.json
npm install
Why is this dependency installed?
Why is this dependency installed?
npm ls package-name
yarn why package-name
npm ls package-name
yarn why package-name
Find security issues
Find security issues
npm audit
snyk test
npm audit
snyk test
Update all dependencies to latest
Update all dependencies to latest
npx npm-check-updates -u
npm install
undefinednpx npm-check-updates -u
npm install
undefined