dependency-upgrade

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Dependency 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 version
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 version

Dependency Analysis

依赖项分析

Audit Dependencies

审计依赖项

bash
undefined
bash
undefined

npm

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
undefined
npx npm-check-updates npx npm-check-updates -u # Update package.json
undefined

Analyze Dependency Tree

分析依赖树

bash
undefined
bash
undefined

See 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/
undefined
npx madge --image graph.png src/
undefined

Compatibility 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
undefined
bash
undefined

1. 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:
  1. TypeScript
  2. React
  3. React Router
  4. Testing libraries
  5. Build tools" > UPGRADE_PLAN.md
undefined
echo "Upgrade order:
  1. TypeScript
  2. React
  3. React Router
  4. Testing libraries
  5. Build tools" > UPGRADE_PLAN.md
undefined

Phase 2: Incremental Updates

阶段2:增量更新

bash
undefined
bash
undefined

Don'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...

undefined
undefined

Phase 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
undefined
bash
undefined

Check the changelog directly

Check the changelog directly

Codemod for Automated Fixes

使用Codemod自动修复

bash
undefined
bash
undefined

Run 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

Dry run to preview changes

Dry run to preview changes

Custom 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@latest
javascript
// Ensure tests pass before and after upgrade
npm run test

// Update test utilities if needed
npm install @testing-library/react@latest

Integration 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
undefined
yaml
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"
undefined
version: 2 updates:
  • package-ecosystem: "npm" directory: "/" schedule: interval: "weekly" open-pull-requests-limit: 5 reviewers:
    • "team-leads" commit-message: prefix: "chore" include: "scope"
undefined

Rollback Plan

回滚计划

javascript
// rollback.sh
#!/bin/bash
javascript
// rollback.sh
#!/bin/bash

Save 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
undefined
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
undefined

Common Upgrade Patterns

常见升级模式

Lock File Management

锁文件管理

bash
undefined
bash
undefined

npm

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
undefined
yarn install --frozen-lockfile # CI mode yarn upgrade-interactive # Interactive upgrades
undefined

Peer Dependency Resolution

对等依赖项解析

bash
undefined
bash
undefined

npm 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
undefined
npm install --force
undefined

Workspace Upgrades

工作区升级

bash
undefined
bash
undefined

Update 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
undefined
npm install package@latest --workspace=packages/app
undefined

Resources

资源

  • 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

最佳实践

  1. Read Changelogs: Understand what changed
  2. Upgrade Incrementally: One major version at a time
  3. Test Thoroughly: Unit, integration, E2E tests
  4. Check Peer Dependencies: Resolve conflicts early
  5. Use Lock Files: Ensure reproducible installs
  6. Automate Updates: Use Renovate or Dependabot
  7. Monitor: Watch for runtime errors post-upgrade
  8. Document: Keep upgrade notes
  1. 阅读变更日志: 了解具体变更内容
  2. 增量升级: 每次升级一个主要版本
  3. 全面测试: 单元测试、集成测试、E2E测试
  4. 检查对等依赖项: 尽早解决冲突
  5. 使用锁文件: 确保可复现的安装
  6. 自动化更新: 使用Renovate或Dependabot
  7. 监控: 升级后关注运行时错误
  8. 文档记录: 保存升级相关笔记

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 production
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 production

Common 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
  • 一次性升级所有依赖项
  • 每次升级后不进行测试
  • 忽略对等依赖项警告
  • 忘记更新锁文件
  • 不阅读破坏性变更说明
  • 跳过主要版本
  • 没有回滚计划