dependency-upgrade
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDependency Upgrade
依赖项升级
Master major dependency version upgrades, compatibility analysis, staged upgrade strategies, and comprehensive testing approaches.
掌握主要依赖版本升级、兼容性分析、分阶段升级策略和全面测试方法。
When to Use This Skill
何时使用此技能
- Upgrading major framework versions
- Updating security-vulnerable dependencies
- Modernizing legacy dependencies
- Resolving dependency conflicts
- Planning incremental upgrade paths
- Testing compatibility matrices
- Automating dependency updates
- 升级主要框架版本
- 更新存在安全漏洞的依赖项
- 现代化遗留依赖项
- 解决依赖项冲突
- 规划增量升级路径
- 测试兼容性矩阵
- 自动化依赖项更新
Semantic Versioning Review
语义化版本回顾
MAJOR.MINOR.PATCH (e.g., 2.3.1)
MAJOR: Breaking changes
MINOR: New features, backward compatible
PATCH: Bug fixes, backward compatible
^2.3.1 = >=2.3.1 <3.0.0 (minor updates)
~2.3.1 = >=2.3.1 <2.4.0 (patch updates)
2.3.1 = exact versionMAJOR.MINOR.PATCH (e.g., 2.3.1)
MAJOR: Breaking changes
MINOR: New features, backward compatible
PATCH: Bug fixes, backward compatible
^2.3.1 = >=2.3.1 <3.0.0 (minor updates)
~2.3.1 = >=2.3.1 <2.4.0 (patch updates)
2.3.1 = exact versionDependency Analysis
依赖项分析
Audit Dependencies
审计依赖项
bash
undefinedbash
undefinednpm
npm
npm outdated
npm audit
npm audit fix
npm outdated
npm audit
npm audit fix
yarn
yarn
yarn outdated
yarn audit
yarn outdated
yarn audit
Check for major updates
Check for major updates
npx npm-check-updates
npx npm-check-updates -u # Update package.json
undefinednpx npm-check-updates
npx npm-check-updates -u # Update package.json
undefinedAnalyze Dependency Tree
分析依赖树
bash
undefinedbash
undefinedSee why a package is installed
See why a package is installed
npm ls package-name
yarn why package-name
npm ls package-name
yarn why package-name
Find duplicate packages
Find duplicate packages
npm dedupe
yarn dedupe
npm dedupe
yarn dedupe
Visualize dependencies
Visualize dependencies
npx madge --image graph.png src/
undefinednpx madge --image graph.png src/
undefinedCompatibility Matrix
兼容性矩阵
javascript
// compatibility-matrix.js
const compatibilityMatrix = {
react: {
"16.x": {
"react-dom": "^16.0.0",
"react-router-dom": "^5.0.0",
"@testing-library/react": "^11.0.0",
},
"17.x": {
"react-dom": "^17.0.0",
"react-router-dom": "^5.0.0 || ^6.0.0",
"@testing-library/react": "^12.0.0",
},
"18.x": {
"react-dom": "^18.0.0",
"react-router-dom": "^6.0.0",
"@testing-library/react": "^13.0.0",
},
},
};
function checkCompatibility(packages) {
// Validate package versions against matrix
}javascript
// compatibility-matrix.js
const compatibilityMatrix = {
react: {
"16.x": {
"react-dom": "^16.0.0",
"react-router-dom": "^5.0.0",
"@testing-library/react": "^11.0.0",
},
"17.x": {
"react-dom": "^17.0.0",
"react-router-dom": "^5.0.0 || ^6.0.0",
"@testing-library/react": "^12.0.0",
},
"18.x": {
"react-dom": "^18.0.0",
"react-router-dom": "^6.0.0",
"@testing-library/react": "^13.0.0",
},
},
};
function checkCompatibility(packages) {
// Validate package versions against matrix
}Staged Upgrade Strategy
分阶段升级策略
Phase 1: Planning
阶段1:规划
bash
undefinedbash
undefined1. Identify current versions
1. Identify current versions
npm list --depth=0
npm list --depth=0
2. Check for breaking changes
2. Check for breaking changes
Read CHANGELOG.md and MIGRATION.md
Read CHANGELOG.md and MIGRATION.md
3. Create upgrade plan
3. Create upgrade plan
echo "Upgrade order:
- TypeScript
- React
- React Router
- Testing libraries
- Build tools" > UPGRADE_PLAN.md
undefinedecho "Upgrade order:
- TypeScript
- React
- React Router
- Testing libraries
- Build tools" > UPGRADE_PLAN.md
undefinedPhase 2: Incremental Updates
阶段2:增量更新
bash
undefinedbash
undefinedDon't upgrade everything at once!
Don't upgrade everything at once!
Step 1: Update TypeScript
Step 1: Update TypeScript
npm install typescript@latest
npm install typescript@latest
Test
Test
npm run test
npm run build
npm run test
npm run build
Step 2: Update React (one major version at a time)
Step 2: Update React (one major version at a time)
npm install react@17 react-dom@17
npm install react@17 react-dom@17
Test again
Test again
npm run test
npm run test
Step 3: Continue with other packages
Step 3: Continue with other packages
npm install react-router-dom@6
npm install react-router-dom@6
And so on...
And so on...
undefinedundefinedPhase 3: Validation
阶段3:验证
javascript
// tests/compatibility.test.js
describe("Dependency Compatibility", () => {
it("should have compatible React versions", () => {
const reactVersion = require("react/package.json").version;
const reactDomVersion = require("react-dom/package.json").version;
expect(reactVersion).toBe(reactDomVersion);
});
it("should not have peer dependency warnings", () => {
// Run npm ls and check for warnings
});
});javascript
// tests/compatibility.test.js
describe("Dependency Compatibility", () => {
it("should have compatible React versions", () => {
const reactVersion = require("react/package.json").version;
const reactDomVersion = require("react-dom/package.json").version;
expect(reactVersion).toBe(reactDomVersion);
});
it("should not have peer dependency warnings", () => {
// Run npm ls and check for warnings
});
});Breaking Change Handling
破坏性变更处理
Identifying Breaking Changes
识别破坏性变更
bash
undefinedbash
undefinedCheck the changelog directly
Check the changelog directly
Codemod for Automated Fixes
使用Codemod自动修复
bash
undefinedbash
undefinedRun jscodeshift with transform URL
Run jscodeshift with transform URL
npx jscodeshift -t <transform-url> <path>
npx jscodeshift -t <transform-url> <path>
Example: Rename unsafe lifecycle methods
Example: Rename unsafe lifecycle methods
For TypeScript files
For TypeScript files
npx jscodeshift -t https://raw.githubusercontent.com/reactjs/react-codemod/master/transforms/rename-unsafe-lifecycles.js --parser=tsx src/
npx jscodeshift -t https://raw.githubusercontent.com/reactjs/react-codemod/master/transforms/rename-unsafe-lifecycles.js --parser=tsx src/
Dry run to preview changes
Dry run to preview changes
npx jscodeshift -t https://raw.githubusercontent.com/reactjs/react-codemod/master/transforms/rename-unsafe-lifecycles.js --dry src/
undefinednpx jscodeshift -t https://raw.githubusercontent.com/reactjs/react-codemod/master/transforms/rename-unsafe-lifecycles.js --dry src/
undefinedCustom Migration Script
自定义迁移脚本
javascript
// migration-script.js
const fs = require("fs");
const glob = require("glob");
glob("src/**/*.tsx", (err, files) => {
files.forEach((file) => {
let content = fs.readFileSync(file, "utf8");
// Replace old API with new API
content = content.replace(
/componentWillMount/g,
"UNSAFE_componentWillMount",
);
// Update imports
content = content.replace(
/import { Component } from 'react'/g,
"import React, { Component } from 'react'",
);
fs.writeFileSync(file, content);
});
});javascript
// migration-script.js
const fs = require("fs");
const glob = require("glob");
glob("src/**/*.tsx", (err, files) => {
files.forEach((file) => {
let content = fs.readFileSync(file, "utf8");
// Replace old API with new API
content = content.replace(
/componentWillMount/g,
"UNSAFE_componentWillMount",
);
// Update imports
content = content.replace(
/import { Component } from 'react'/g,
"import React, { Component } from 'react'",
);
fs.writeFileSync(file, content);
});
});Testing Strategy
测试策略
Unit Tests
单元测试
javascript
// Ensure tests pass before and after upgrade
npm run test
// Update test utilities if needed
npm install @testing-library/react@latestjavascript
// Ensure tests pass before and after upgrade
npm run test
// Update test utilities if needed
npm install @testing-library/react@latestIntegration Tests
集成测试
javascript
// tests/integration/app.test.js
describe("App Integration", () => {
it("should render without crashing", () => {
render(<App />);
});
it("should handle navigation", () => {
const { getByText } = render(<App />);
fireEvent.click(getByText("Navigate"));
expect(screen.getByText("New Page")).toBeInTheDocument();
});
});javascript
// tests/integration/app.test.js
describe("App Integration", () => {
it("should render without crashing", () => {
render(<App />);
});
it("should handle navigation", () => {
const { getByText } = render(<App />);
fireEvent.click(getByText("Navigate"));
expect(screen.getByText("New Page")).toBeInTheDocument();
});
});Visual Regression Tests
视觉回归测试
javascript
// visual-regression.test.js
describe("Visual Regression", () => {
it("should match snapshot", () => {
const { container } = render(<App />);
expect(container.firstChild).toMatchSnapshot();
});
});javascript
// visual-regression.test.js
describe("Visual Regression", () => {
it("should match snapshot", () => {
const { container } = render(<App />);
expect(container.firstChild).toMatchSnapshot();
});
});E2E Tests
E2E测试
javascript
// cypress/e2e/app.cy.js
describe("E2E Tests", () => {
it("should complete user flow", () => {
cy.visit("/");
cy.get('[data-testid="login"]').click();
cy.get('input[name="email"]').type("user@example.com");
cy.get('button[type="submit"]').click();
cy.url().should("include", "/dashboard");
});
});javascript
// cypress/e2e/app.cy.js
describe("E2E Tests", () => {
it("should complete user flow", () => {
cy.visit("/");
cy.get('[data-testid="login"]').click();
cy.get('input[name="email"]').type("user@example.com");
cy.get('button[type="submit"]').click();
cy.url().should("include", "/dashboard");
});
});Automated Dependency Updates
自动化依赖项更新
Renovate Configuration
Renovate配置
json
// renovate.json
{
"extends": ["config:base"],
"packageRules": [
{
"matchUpdateTypes": ["minor", "patch"],
"automerge": true
},
{
"matchUpdateTypes": ["major"],
"automerge": false,
"labels": ["major-update"]
}
],
"schedule": ["before 3am on Monday"],
"timezone": "America/New_York"
}json
// renovate.json
{
"extends": ["config:base"],
"packageRules": [
{
"matchUpdateTypes": ["minor", "patch"],
"automerge": true
},
{
"matchUpdateTypes": ["major"],
"automerge": false,
"labels": ["major-update"]
}
],
"schedule": ["before 3am on Monday"],
"timezone": "America/New_York"
}Dependabot Configuration
Dependabot配置
yaml
undefinedyaml
undefined.github/dependabot.yml
.github/dependabot.yml
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 5
reviewers:
- "team-leads" commit-message: prefix: "chore" include: "scope"
undefinedversion: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 5
reviewers:
- "team-leads" commit-message: prefix: "chore" include: "scope"
undefinedRollback Plan
回滚计划
javascript
// rollback.sh
#!/bin/bashjavascript
// rollback.sh
#!/bin/bashSave current state
Save current state
git stash
git checkout -b upgrade-branch
git stash
git checkout -b upgrade-branch
Attempt upgrade
Attempt upgrade
npm install package@latest
npm install package@latest
Run tests
Run tests
if npm run test; then
echo "Upgrade successful"
git add package.json package-lock.json
git commit -m "chore: upgrade package"
else
echo "Upgrade failed, rolling back"
git checkout main
git branch -D upgrade-branch
npm install # Restore from package-lock.json
fi
undefinedif npm run test; then
echo "Upgrade successful"
git add package.json package-lock.json
git commit -m "chore: upgrade package"
else
echo "Upgrade failed, rolling back"
git checkout main
git branch -D upgrade-branch
npm install # Restore from package-lock.json
fi
undefinedCommon Upgrade Patterns
常见升级模式
Lock File Management
锁文件管理
bash
undefinedbash
undefinednpm
npm
npm install --package-lock-only # Update lock file only
npm ci # Clean install from lock file
npm install --package-lock-only # Update lock file only
npm ci # Clean install from lock file
yarn
yarn
yarn install --frozen-lockfile # CI mode
yarn upgrade-interactive # Interactive upgrades
undefinedyarn install --frozen-lockfile # CI mode
yarn upgrade-interactive # Interactive upgrades
undefinedPeer Dependency Resolution
对等依赖项解析
bash
undefinedbash
undefinednpm 7+: strict peer dependencies
npm 7+: strict peer dependencies
npm install --legacy-peer-deps # Ignore peer deps
npm install --legacy-peer-deps # Ignore peer deps
npm 8+: override peer dependencies
npm 8+: override peer dependencies
npm install --force
undefinednpm install --force
undefinedWorkspace Upgrades
工作区升级
bash
undefinedbash
undefinedUpdate all workspace packages
Update all workspace packages
npm install --workspaces
npm install --workspaces
Update specific workspace
Update specific workspace
npm install package@latest --workspace=packages/app
undefinednpm install package@latest --workspace=packages/app
undefinedResources
资源
- references/semver.md: Semantic versioning guide
- references/compatibility-matrix.md: Common compatibility issues
- references/staged-upgrades.md: Incremental upgrade strategies
- references/testing-strategy.md: Comprehensive testing approaches
- assets/upgrade-checklist.md: Step-by-step checklist
- assets/compatibility-matrix.csv: Version compatibility table
- scripts/audit-dependencies.sh: Dependency audit script
- references/semver.md: 语义化版本指南
- references/compatibility-matrix.md: 常见兼容性问题
- references/staged-upgrades.md: 增量升级策略
- references/testing-strategy.md: 全面测试方法
- assets/upgrade-checklist.md: 分步检查清单
- assets/compatibility-matrix.csv: 版本兼容性表
- scripts/audit-dependencies.sh: 依赖项审计脚本
Best Practices
最佳实践
- Read Changelogs: Understand what changed
- Upgrade Incrementally: One major version at a time
- Test Thoroughly: Unit, integration, E2E tests
- Check Peer Dependencies: Resolve conflicts early
- Use Lock Files: Ensure reproducible installs
- Automate Updates: Use Renovate or Dependabot
- Monitor: Watch for runtime errors post-upgrade
- Document: Keep upgrade notes
- 阅读变更日志: 了解具体变更内容
- 增量升级: 每次升级一个主要版本
- 全面测试: 单元测试、集成测试、E2E测试
- 检查对等依赖项: 尽早解决冲突
- 使用锁文件: 确保可复现的安装
- 自动化更新: 使用Renovate或Dependabot
- 监控: 升级后关注运行时错误
- 文档记录: 保存升级相关笔记
Upgrade Checklist
升级检查清单
markdown
Pre-Upgrade:
- [ ] Review current dependency versions
- [ ] Read changelogs for breaking changes
- [ ] Create feature branch
- [ ] Backup current state (git tag)
- [ ] Run full test suite (baseline)
During Upgrade:
- [ ] Upgrade one dependency at a time
- [ ] Update peer dependencies
- [ ] Fix TypeScript errors
- [ ] Update tests if needed
- [ ] Run test suite after each upgrade
- [ ] Check bundle size impact
Post-Upgrade:
- [ ] Full regression testing
- [ ] Performance testing
- [ ] Update documentation
- [ ] Deploy to staging
- [ ] Monitor for errors
- [ ] Deploy to productionmarkdown
Pre-Upgrade:
- [ ] Review current dependency versions
- [ ] Read changelogs for breaking changes
- [ ] Create feature branch
- [ ] Backup current state (git tag)
- [ ] Run full test suite (baseline)
During Upgrade:
- [ ] Upgrade one dependency at a time
- [ ] Update peer dependencies
- [ ] Fix TypeScript errors
- [ ] Update tests if needed
- [ ] Run test suite after each upgrade
- [ ] Check bundle size impact
Post-Upgrade:
- [ ] Full regression testing
- [ ] Performance testing
- [ ] Update documentation
- [ ] Deploy to staging
- [ ] Monitor for errors
- [ ] Deploy to productionCommon Pitfalls
常见陷阱
- Upgrading all dependencies at once
- Not testing after each upgrade
- Ignoring peer dependency warnings
- Forgetting to update lock file
- Not reading breaking change notes
- Skipping major versions
- Not having rollback plan
- 一次性升级所有依赖项
- 每次升级后不进行测试
- 忽略对等依赖项警告
- 忘记更新锁文件
- 不阅读破坏性变更说明
- 跳过主要版本
- 没有回滚计划