You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins流水线中Angular 9能否复用测试阶段的构建产物?

如何在Jenkins流水线中复用Angular测试构建产物以减少重复构建时间

你的想法完全站得住脚——如果测试阶段的构建产物和生产构建不一致,单元测试的有效性确实会大打折扣,而且两次重复构建纯粹是在浪费时间。下面是几种可行的解决方案,帮你把整体构建时长压缩到2分钟左右:

方案1:利用Angular CLI的内置构建缓存

Angular CLI从6.x版本开始默认启用了构建缓存,缓存文件存放在node_modules/.angular/cache目录下。只要两次构建的依赖、配置和环境完全一致,第二次构建会直接复用缓存的编译结果,速度能提升80%以上。

具体操作:

  1. 在Jenkins声明式流水线中,添加缓存node_modules/.angular/cache的步骤:
    pipeline {
      agent any
      options {
        cache(path: 'node_modules/.angular/cache', key: "angular-cache-\${checksum 'package-lock.json'}", restoreKeys: ['angular-cache-'])
      }
      stages {
        // 前置步骤:安装依赖等
        stage('Run Production Tests') {
          steps {
            sh 'node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng test --prod --no-watch --no-progress'
          }
        }
        stage('Build Production Bundle') {
          steps {
            sh 'node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng build --prod'
          }
        }
      }
    }
    
  2. 给测试命令加上--no-watch --no-progress,适配Jenkins的非交互式运行环境。

调整后,第二次构建(ng build --prod)会复用测试阶段的缓存,几乎不需要重新编译,耗时会从2分钟降到几十秒。

方案2:先构建一次,再基于构建产物跑测试

这种方式彻底避免重复构建:先执行生产构建,再让测试直接使用已生成的构建产物,而不是重新构建一遍应用。

具体操作:

  1. 修改angular.json配置文件,让test目标指向生产构建的输出:
    "projects": {
      "your-project-name": {
        "architect": {
          "test": {
            "builder": "@angular-devkit/build-angular:karma",
            "options": {
              // 指向生产构建的目标
              "buildTarget": "your-project-name:build:production",
              "watch": false
            }
          }
        }
      }
    }
    
  2. 调整Jenkins流水线的步骤顺序:
    stages {
      stage('Build Production Bundle') {
        steps {
          sh 'node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng build --prod'
        }
      }
      stage('Run Production Tests') {
        steps {
          sh 'node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng test --prod'
        }
      }
    }
    

现在测试阶段会直接复用已经构建好的生产包,不会再触发新的构建,整体流程只需要一次2分钟的构建。

方案3:直接复用测试阶段的构建产物(如果已输出)

默认情况下ng test不会把构建产物输出到dist目录,但你可以修改配置让它输出,然后跳过后续的ng build步骤:

  1. 在angular.json的test配置中添加outputPath:
    "test": {
      "options": {
        "outputPath": "dist/test",
        // 其他配置保持和生产构建一致
      }
    }
    
  2. 测试完成后,将dist/test的产物复制到生产构建的默认目录,直接跳过ng build步骤:
    stages {
      stage('Run Production Tests & Generate Bundle') {
        steps {
          sh 'node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng test --prod --no-watch --no-progress'
          sh 'cp -r dist/test/* dist/'
        }
      }
      // 后续直接使用dist目录的产物即可,无需单独构建
    }
    

注意:这种方式需要确保test的构建配置和build:prod完全一致(比如AOT编译、代码压缩、环境变量等),否则产物可能不符合生产要求。


内容的提问来源于stack exchange,提问作者scipper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:31:08