web前端插件包依赖包自动化离线打包脚本(.tzg)

46 阅读5分钟

ImportTgz.ps1:Element Plus 依赖自动化依赖包离线打包脚本

一、脚本简介

ImportTgz.ps1 是一个用于自动化打包 Element Plus 及其所有依赖为 .tgz 文件的 PowerShell 脚本,专为离线部署场景设计。

核心功能

  • ✅ 自动检测当前项目使用的 Element Plus 版本
  • ✅ 递归收集所有直接和间接依赖
  • ✅ 生成标准的 npm 包文件(.tgz)
  • ✅ 支持多种 package.json 配置
  • ✅ 生成详细的打包报告

二、核心设计思路

1. 版本自动检测机制

  • 优先从项目 package.json 读取 Element Plus 版本
  • 若未找到,从 node_modules 获取精确安装版本
  • 提供默认版本作为兜底方案

2. 递归依赖收集

  • 从 Element Plus 开始,递归遍历所有依赖树
  • 去重处理,确保每个依赖只打包一次
  • 支持复杂依赖关系

3. 模块化设计

  • 清晰的功能划分:版本检测、依赖收集、打包执行
  • 可复用的辅助函数
  • 详细的日志输出

三、详细实现步骤

步骤 1:脚本初始化与配置

# No parameters required
param()

$outputDir = ".\deps-tgz"
$skipFailures = $true

# Auto detect element-plus from package.json or node_modules
$epName = "element-plus"
$epVersion = $null

关键说明 :

  • 设置输出目录为 ./deps-tgz
  • 配置失败跳过选项,确保部分依赖失败不影响整体流程
  • 初始化 Element Plus 名称和版本变量

步骤 2:版本自动检测

# Try to get version from package.json first
if (Test-Path -Path ".\package.json") {
    $pkgJson = Get-Content -Path ".\package.json" -Raw -Encoding UTF8
    $pkg $pkgJson | ConvertFrom-Json -ErrorAction SilentlyContinue
    
    if ($pkg -and $pkg.dependencies -and $pkg.dependencies.$epName) {
        $epVersion $pkg.dependencies.$epName
        Write-Host "✅ element-plus version from package.json: $epVersion" 
        -ForegroundColor Green
    } elseif ($pkg -and $pkg.devDependencies -and $pkg.devDependencies.
    $epName) {
        $epVersion $pkg.devDependencies.$epName
        Write-Host "✅ element-plus version from devDependencies: $epVersion" 
        -ForegroundColor Green
    }
}

# If not found in package.json, try to get from node_modules
if (-not $epVersion -and (Test-Path -Path ".\node_modules\$epName\package.
json")) {
    $epPkgJson = Get-Content -Path ".\node_modules\$epName\package.json" 
    -Raw -Encoding UTF8
    $epPkg $epPkgJson | ConvertFrom-Json -ErrorAction SilentlyContinue
    if ($epPkg -and $epPkg.version) {
        $epVersion $epPkg.version
        Write-Host "✅ element-plus version from node_modules: $epVersion" 
        -ForegroundColor Green
    }
}

# If still not found, use default version
if (-not $epVersion) {
    $epVersion "2.13.0" # Default version as fallback
    Write-Host "ℹ️ Using default element-plus version: $epVersion" 
    -ForegroundColor Yellow
}

关键说明 :

  • 使用 Test-Path 检查文件是否存在
  • 使用 Get-Content -Raw 读取完整 JSON 内容
  • 使用 ConvertFrom-Json 解析 JSON
  • 依次从 dependencies 、 devDependencies 和 node_modules 获取版本
  • 提供默认版本作为后备方案

步骤 3:输出目录准备

# Create output directory
if (-not (Test-Path -Path $outputDir)) {
    New-Item -Path $outputDir -ItemType Directory | Out-Null
    Write-Host "✅ Output directory created: $outputDir" -ForegroundColor 
    Green
}

关键说明 :

  • 检查输出目录是否存在
  • 不存在则创建,确保后续打包操作有正确的输出位置

步骤 4:依赖收集核心逻辑 4.1 辅助函数:获取精确版本

# Helper function to get exact version from node_modules
function Get-ExactVersion {
    param($packageName)
    $packageJsonPath = ".\node_modules\$packageName\package.json"
    if (Test-Path -Path $packageJsonPath) {
        $pkgJson = Get-Content -Path $packageJsonPath -Raw -Encoding UTF8
        $pkg = $pkgJson | ConvertFrom-Json -ErrorAction SilentlyContinue
        if ($pkg -and $pkg.version) {
            Write-Host "      ✓ $packageName version: $($pkg.version)" 
            -ForegroundColor Gray
            return $pkg.version
        } else {
            Write-Host "      ✗ $packageName has no valid version" 
            -ForegroundColor Gray
        }
    } else {
        Write-Host "      ✗ $packageName package.json not found" 
        -ForegroundColor Gray
    }
    return $null
}

关键说明 :

  • 接收包名参数,返回精确版本号
  • 检查 node_modules 中对应包的 package.json
  • 详细日志输出,便于调试 4.2 核心函数:递归收集依赖
# Recursive function to collect all dependencies
function Collect-Deps {
    param($packageName)
    Write-Host "   Collecting: $packageName" -ForegroundColor Gray
    $exactVersion = Get-ExactVersion -packageName $packageName
    
    if ($exactVersion) {
        $depId "$packageName@$exactVersion"
        if ($script:allDeps -notcontains $depId) {
            $script:allDeps += $depId
            Write-Host "   Added: $depId" -ForegroundColor Gray
            
            # Read this package's dependencies and collect them recursively
            $pkgJsonPath ".\node_modules\$packageName\package.json"
            $pkgJson = Get-Content -Path $pkgJsonPath -Raw -Encoding UTF8
            $pkg $pkgJson | ConvertFrom-Json -ErrorAction SilentlyContinue
            
            if ($pkg -and $pkg.dependencies) {
                $depCount $pkg.dependencies.PSObject.Properties.Count
                Write-Host "   $packageName has $depCount dependencies" 
                -ForegroundColor Gray
                foreach ($depProp in $pkg.dependencies.PSObject.Properties) {
                    Collect-Deps -packageName $depProp.Name
                }
            } else {
                Write-Host "   $packageName has no dependencies" 
                -ForegroundColor Gray
            }
        } else {
            Write-Host "   Already exists: $depId" -ForegroundColor Gray
        }
    } else {
        Write-Host "   Skipping: $packageName (no version found)" 
        -ForegroundColor Gray
    }
}

关键说明 :

  • 使用 $script: 作用域修饰符,确保函数内部可访问全局数组
  • 递归遍历依赖树,收集所有直接和间接依赖
  • 去重处理,避免重复打包
  • 详细的日志输出,展示收集过程 4.3 执行依赖收集
# Start with element-plus itself
Collect-Deps -packageName "element-plus"

# Add direct dependencies from element-plus package.json if they're not 
already added
if ($epPackage.dependencies) {
    Write-Host "   Adding direct dependencies from element-plus package.
    json..." -ForegroundColor Gray
    foreach ($depName in $epPackage.dependencies.PSObject.Properties.Name) {
        Collect-Deps -packageName $depName
    }
}

关键说明 :

  • 从 Element Plus 开始收集
  • 额外处理 Element Plus 的直接依赖,确保完整性
  • 双重保险机制,避免遗漏依赖

步骤 5:依赖打包执行

# Package dependencies
Write-Host "📦 Starting packaging..." -ForegroundColor Cyan
$successCount = 0
$failCount = 0
$failedDeps = @()

foreach ($dep in $uniqueDeps) {
    Write-Host "`nProcessing: $dep" -ForegroundColor Gray
    try {
        # Use npm pack to create tarball
        $packOutput = npm pack $dep --pack-destination $outputDir 2>&1
        if ($LASTEXITCODE -eq 0) {
            $successCount++
            Write-Host "✅ Success: $dep" -ForegroundColor Green
        } else {
            $failCount++
            $failedDeps += $dep
            Write-Host "❌ Failed: $dep" -ForegroundColor Red
            if (-not $skipFailures) { exit 1 }
        }
    } catch {
        $failCount++
        $failedDeps += $dep
        Write-Host "❌ Failed: $dep" -ForegroundColor Red
        if (-not $skipFailures) { exit 1 }
    }
}

关键说明 :

  • 使用 npm pack 命令生成标准 .tgz 包
  • 支持失败跳过,提高脚本健壮性
  • 统计成功和失败数量
  • 捕获异常,确保脚本稳定运行

步骤 6:生成打包报告

# Final report
Write-Host "`n==================================================" 
-ForegroundColor Cyan
Write-Host "📊 Packaging Report" -ForegroundColor Cyan
Write-Host "==================================================" 
-ForegroundColor Cyan
Write-Host "✅ Success: $successCount items" -ForegroundColor Green
Write-Host "❌ Failed: $failCount items" -ForegroundColor Red
if ($failedDeps.Count -gt 0) {
    Write-Host "⚠️  Failed list: " -ForegroundColor Yellow
    $failedDeps | ForEach-Object { Write-Host "   - $_" -ForegroundColor 
    Yellow }
}
Write-Host "📁 Output path: $((Get-Item $outputDir).FullName)" 
-ForegroundColor Cyan
Write-Host "==================================================" 
-ForegroundColor Cyan

关键说明 :

  • 清晰的报告格式
  • 成功/失败数量统计
  • 失败依赖列表
  • 输出目录绝对路径

四、技术亮点

1. 版本自动适配

  • 支持语义化版本(如 ^2.11.7)
  • 自动解析为精确版本(如 2.11.7)
  • 适配不同项目配置

2. 强大的错误处理

  • 多级异常捕获
  • 详细的错误信息
  • 失败跳过机制
  • 完整的错误报告

3. 详细的日志系统

  • 彩色日志输出,区分不同级别
  • 步骤化日志,便于追踪执行流程
  • 调试级别的详细信息
  • 友好的用户反馈

4. 兼容性设计

  • 支持 PowerShell 5.1+
  • 兼容多种 npm 版本
  • 支持不同的 package-lock.json 格式
  • 跨平台设计理念

五、使用方法

1. 前置条件

  • 已安装 Node.js 和 npm
  • 已执行 npm install 安装项目依赖
  • Windows 系统或支持 PowerShell 的环境

2. 执行步骤

  1. 将 ImportTgz.ps1 脚本放入项目根目录
  2. 打开 PowerShell 终端
  3. 执行命令: powershell -ExecutionPolicy Bypass -File .\ImportTgz.ps1

3. 输出示例

✅ element-plus version from package.json: ^2.11.7
🔍 Parsing dependencies...
   Getting element-plus dependencies...
   ...
✅ Found 20 unique dependencies (including Element Plus)
📦 Starting packaging...

Processing: @ctrl/tinycolor@3.6.1
✅ Success: @ctrl/tinycolor@3.6.1
...

==================================================
📊 Packaging Report
==================================================
✅ Success: 20 items
❌ Failed: 0 items
📁 Output path: E:\PROJECT\deps-tgz
==================================================

六、常见问题及解决方案

问题 1:脚本执行权限不足

解决方案 :使用 -ExecutionPolicy Bypass 参数执行脚本

powershell -ExecutionPolicy Bypass -File .\ImportTgz.ps1

问题 2:部分依赖打包失败

解决方案 :

  • 检查网络连接
  • 确保 npm 配置正确
  • 脚本默认跳过失败项,可通过修改 skipFailures=skipFailures = false 强制停止

问题 3:找不到 element-plus 版本

解决方案 :

  • 确保项目已安装 element-plus
  • 检查 package.json 配置
  • 脚本会使用默认版本兜底

七、总结与扩展建议

脚本优势

  • 🚀 自动化程度高,减少手动操作
  • 📦 生成标准 npm 包,便于离线部署
  • 📊 详细报告,便于问题追踪
  • 🔧 模块化设计,易于维护和扩展

扩展建议

  1. 支持更多 UI 库 :扩展为通用依赖打包工具,支持其他 UI 库
  2. 配置文件支持 :添加外部配置文件,支持自定义输出目录、过滤规则等
  3. 增量打包 :添加增量打包功能,只打包新增或修改的依赖
  4. 压缩优化 :添加打包后压缩功能,减少文件体积
  5. 跨平台支持 :移植到 Shell 脚本,支持 Linux/Mac 环境

适用场景

  • 离线部署环境
  • 内网开发环境
  • 依赖版本锁定
  • CI/CD 自动化流程
  • 多项目依赖共享

八、完整脚本获取

完整脚本可通过以下方式获取:

  • 复制本文中的代码片段
  • 访问项目仓库获取最新版本
  • 根据需求定制修改 结语 :ImportTgz.ps1 脚本提供了一种高效、可靠的方式来管理 Element Plus 依赖,特别适合离线部署场景。通过自动化脚本,可以减少手动操作的错误,提高工作效率,确保依赖版本的一致性和完整性。

最终结果

企业微信截图_20260123181425.png

希望本文能对您的项目有所帮助!如果您有任何建议或改进意见,欢迎在评论区交流。