Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jenkins 结合 Angular 展示构建版本 #116

Open
reng99 opened this issue May 21, 2022 · 0 comments
Open

Jenkins 结合 Angular 展示构建版本 #116

reng99 opened this issue May 21, 2022 · 0 comments
Labels

Comments

@reng99
Copy link
Owner

reng99 commented May 21, 2022

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第1天,点击查看活动详情

刚好最近在巩固相关的知识内容,以 angular 为主,那么咱就来参与下活动,希望能够坚持下去,顺便拿点小奖励。

I am In.

Angular 结合 Git Commit 版本处理 文末我们留下了疑问🤔️ 下面将问题具体化

结合 jenkins 构建,我们能够获取到构建的信息,比如构建号,回填到页面否?

如下:

build_number.png

Uha,我们在原基础上修改下。

根目录添加文件 build_info.json

{}

你没看错,build_info.json 的内容就是 {}

build_info.json 文件是给 Jenkinsfile 构建的时候生成的。

具体的实现思路如下:

  1. 在构建的过程中执行 Jenkinsfile 生成 build_info.json 文件
  2. 在对项目打包的时候,针对不同的环境考虑是否获取 build_info.json 文件的内容

为了方便演示,这里的环境只考虑生产环境

上面的步骤简单两步,最重要的一点是如何写入 build_info.json 文件内容

如果你不熟悉 Jenkinsfile 相关内容,请结合Jenkins Pipeline 结合 Gitlab 实现 Node 项目自动构建文章来阅读。此时你关注的重点是文章 Jenkinsfile 的内容,如下:

pipeline {
    agent any
    
    tools { 
        nodejs "nodejs" 
    }
    
    stages {
        stage('Dependency') {
            steps {
                sh 'npm install'
            }
        }
        # 我们在此添加过一个 stage,见下面👇
        stage('Build') { 
            steps {
                sh 'npm run clean' 
                sh 'npm run build' 
            }
        }
    }
}

我们添加过一个 stage 来完成我们对 build_info.json 文件的写入。

stage('Version') {
  steps {
    script {
      def amap = 
        'build_number': BUILD_NUMBER, # 构建号
        'job_name': JOB_NAME # 任务名称
      ]
      
      # 写入文件
      writeJSON file: WORKSPACE+'build_info.json', json: amap # WORKSPACE 根目录
    }
  }
}

Yeah,思路还可以... Right?

下面进入第二步骤:读取 build_info.json 的内容,我截取 version.js 生产环境那部分的内容:

// 引入生成的 build_info.json 文件
let buildInfo = require('./build_info.json');

if(config.env === 'production') { 
    // 获取构建的版本号,否则获取默认的版本
    versionObj.version = buildInfo.build_number || config.version 
}

完成上面的文件之后,你就可以发布到相关的环境,顺利的话,在页面上你可以看到相关的版本号了。

这篇文章跟 angular 的关联不是很大,只是用来打配合 jenkins。下一篇文章是关于使用 Angular 进行 spa 开发的内容,敬请期待。

【完】✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant