如何用脚本批量检查包冲突?

wen 实用脚本 2

本文目录导读:

如何用脚本批量检查包冲突?

  1. npm 包冲突检查
  2. 批量检查多个项目
  3. 使用 npm-check 工具
  4. 高级冲突检测脚本
  5. 持续集成中的冲突检查
  6. 多包管理器支持
  7. 使用说明

我来介绍几种批量检查包冲突的脚本方法,针对不同的包管理器:

npm 包冲突检查

基础冲突检测脚本

#!/bin/bash
# check-npm-conflicts.sh
echo "检查 npm 包冲突..."
npm ls 2>&1 | grep -E "UNMET DEPENDENCY|CONFLICT|ERESOLVE" || echo "未发现冲突"

深度冲突分析脚本

#!/bin/bash
# deep-check-conflicts.sh
PROJECT_DIR=$1
if [ -z "$PROJECT_DIR" ]; then
    echo "用法: ./deep-check-conflicts.sh <项目目录>"
    exit 1
fi
cd "$PROJECT_DIR"
echo "=== 1. 检查基础依赖 ==="
npm list --depth=0 2>&1
echo -e "\n=== 2. 检查深度依赖冲突 ==="
npm ls 2>&1 | grep -E "UNMET|CONFLICT|ERESOLVE|while resolving|peer dependencies"
echo -e "\n=== 3. 检查版本不兼容 ==="
npm outdated 2>&1
echo -e "\n=== 4. 生成依赖树报告 ==="
npm list --all > dependency-tree.txt 2>&1
echo "依赖树已保存到 dependency-tree.txt"

批量检查多个项目

批量扫描脚本

#!/bin/bash
# batch-check-projects.sh
# 要扫描的项目目录列表
PROJECTS=(
    "/path/to/project1"
    "/path/to/project2"
    "/path/to/project3"
)
for project in "${PROJECTS[@]}"; do
    echo "========== 检查项目: $project =========="
    if [ -f "$project/package.json" ]; then
        cd "$project"
        # 安装依赖(如果需要)
        # npm install --dry-run 2>&1 | grep -E "CONFLICT|ERESOLVE"
        # 检查已安装的依赖冲突
        result=$(npm ls 2>&1 | grep -E "UNMET|CONFLICT|ERESOLVE")
        if [ -n "$result" ]; then
            echo "⚠️  发现冲突:"
            echo "$result"
        else
            echo "✅ 未发现冲突"
        fi
    else
        echo "❌ 未找到 package.json"
    fi
    echo ""
done

使用 npm-check 工具

安装并使用

#!/bin/bash
# install-and-check.sh
# 安装全局工具
npm install -g npm-check
echo "检查依赖更新和冲突..."
npm-check --skip-unused 2>&1 | grep -E "update|conflict|warning|error"

高级冲突检测脚本

#!/usr/bin/env node
// advanced-conflict-checker.js
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
class DependencyConflictChecker {
    constructor(projectPath) {
        this.projectPath = projectPath;
        this.conflicts = [];
    }
    checkPackageJson() {
        const packagePath = path.join(this.projectPath, 'package.json');
        if (!fs.existsSync(packagePath)) {
            console.error('❌ 未找到 package.json');
            return false;
        }
        return true;
    }
    checkDirectConflicts() {
        console.log('检查直接依赖冲突...');
        try {
            const result = execSync('npm ls --depth=0', {
                cwd: this.projectPath,
                encoding: 'utf8'
            });
            console.log(result);
        } catch (error) {
            this.conflicts.push({
                type: 'direct',
                message: error.message
            });
        }
    }
    checkTransitiveConflicts() {
        console.log('检查传递依赖冲突...');
        try {
            const result = execSync('npm ls 2>&1 | grep -E "UNMET|CONFLICT|ERESOLVE"', {
                cwd: this.projectPath,
                shell: true,
                encoding: 'utf8'
            });
            if (result.trim()) {
                this.conflicts.push({
                    type: 'transitive',
                    message: result
                });
            }
        } catch (error) {
            // grep 可能返回非零退出码
        }
    }
    checkPeerDependencies() {
        console.log('检查对等依赖...');
        const packageJson = JSON.parse(
            fs.readFileSync(path.join(this.projectPath, 'package.json'), 'utf8')
        );
        const deps = {...packageJson.dependencies, ...packageJson.devDependencies};
        const peerDeps = packageJson.peerDependencies || {};
        for (const [pkg, version] of Object.entries(peerDeps)) {
            if (deps[pkg] && deps[pkg] !== version) {
                this.conflicts.push({
                    type: 'peer',
                    package: pkg,
                    expected: version,
                    found: deps[pkg]
                });
            }
        }
    }
    generateConflictReport() {
        console.log('\n=== 冲突报告 ===');
        if (this.conflicts.length === 0) {
            console.log('✅ 未发现任何冲突');
            return;
        }
        this.conflicts.forEach((conflict, index) => {
            console.log(`\n冲突 ${index + 1}:`);
            console.log(`类型: ${conflict.type}`);
            console.log(`详情:`, conflict.message || conflict);
        });
        console.log(`\n共发现 ${this.conflicts.length} 个冲突`);
    }
    run() {
        console.log(`开始检查项目: ${this.projectPath}`);
        if (!this.checkPackageJson()) return;
        this.checkDirectConflicts();
        this.checkTransitiveConflicts();
        this.checkPeerDependencies();
        this.generateConflictReport();
    }
}
// 使用示例
const checker = new DependencyConflictChecker('/path/to/your/project');
checker.run();

持续集成中的冲突检查

# .github/workflows/conflict-check.yml
name: Dependency Conflict Check
on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]
jobs:
  check-conflicts:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - name: Setup Node.js
      uses: actions/setup-node@v3
      with:
        node-version: '18'
    - name: Install dependencies
      run: |
        npm ci --ignore-scripts 2>&1 | head -50
      continue-on-error: true
    - name: Check for conflicts
      run: |
        npm ls 2>&1 | grep -E "UNMET|CONFLICT|ERESOLVE" || echo "No conflicts found"
    - name: Generate conflict report
      if: failure()
      run: |
        npm ls --all > conflict-report.txt
        echo "冲突报告已保存"
    - name: Upload report
      if: failure()
      uses: actions/upload-artifact@v3
      with:
        name: conflict-report
        path: conflict-report.txt

多包管理器支持

#!/bin/bash
# universal-check.sh
check_npm() {
    cd "$1"
    echo "检查 npm 依赖..."
    npm ls 2>&1 | grep -E "UNMET|CONFLICT|ERESOLVE"
}
check_yarn() {
    cd "$1"
    echo "检查 yarn 依赖..."
    yarn check --integrity 2>&1 || true
    yarn list --depth=0 2>&1 | grep -E "warning|conflict"
}
check_pnpm() {
    cd "$1"
    echo "检查 pnpm 依赖..."
    pnpm list --depth=0 2>&1 | grep -E "missing|conflict"
}
# 根据 lock 文件选择检查方式
PROJECT_DIR="${1:-.}"
if [ -f "$PROJECT_DIR/yarn.lock" ]; then
    check_yarn "$PROJECT_DIR"
elif [ -f "$PROJECT_DIR/pnpm-lock.yaml" ]; then
    check_pnpm "$PROJECT_DIR"
elif [ -f "$PROJECT_DIR/package-lock.json" ]; then
    check_npm "$PROJECT_DIR"
else
    echo "未知的包管理器"
    exit 1
fi

使用说明

  1. 直接运行脚本:

    chmod +x check-npm-conflicts.sh
    ./check-npm-conflicts.sh
  2. 批量扫描:

    ./batch-check-projects.sh
  3. Node.js 版本:

    node advanced-conflict-checker.js

这些脚本可以帮助你快速发现和定位包冲突问题,建议在 CI/CD 流程中集成使用。

抱歉,评论功能暂时关闭!