搜尋
首頁web前端js教程Angular怎麼結合Git Commit進行版本處理

這篇文章帶大家繼續angular的學習,介紹一下Angular 結合 Git Commit 版本處理的方法,希望對大家有幫助!

Angular怎麼結合Git Commit進行版本處理

Angular怎麼結合Git Commit進行版本處理

上圖是頁面上展示的測試環境/開發環境版本資訊。 【相關教學推薦:《angular教學》】

後面有介紹

Angular怎麼結合Git Commit進行版本處理

##上圖表示的是每次提交的

Git Commit的信息,當然,這裡我是每次提交都記錄,你可以在每次構建的時候記錄。

So,我們接下來用

Angular 實作下效果,ReactVue 同理。

搭建環境

因為這裡的重點不是搭建環境,我們直接用

angular-cli 鷹架直接產生一個專案就可以了。

Step 1: 安裝鷹架工具

npm install -g @angular/cli

Step 2: 建立一個專案

# ng new PROJECT_NAME
ng new ng-commit

#Step 3:運行項目

npm run start

項目運行起來,預設監聽

4200端口,直接在瀏覽器打開http://localhost:4200/就行了。

4200 埠沒被佔用的前提下

此時,

ng-commit 專案重點資料夾src 的組成如下:

src
├── app                                               // 应用主体
│   ├── app-routing.module.ts                         // 路由模块
│   .
│   └── app.module.ts                                 // 应用模块
├── assets                                            // 静态资源
├── main.ts                                           // 入口文件
.
└── style.less                                        // 全局样式

上面目錄結構,我們後面會在

app 目錄下增加services 服務目錄,和assets 目錄下的version.json檔。

記錄每次提交的資訊

在根目錄建立一個檔案

version.txt,用於儲存提交的資訊;在根目錄建立一個檔案commit.js,用於操作提交資訊。

重點在

commit.js,我們直接進入主題:

const execSync = require('child_process').execSync;
const fs = require('fs')
const versionPath = 'version.txt'
const buildPath = 'dist'
const autoPush = true;
const commit = execSync('git show -s --format=%H').toString().trim(); // 当前的版本号

let versionStr = ''; // 版本字符串

if(fs.existsSync(versionPath)) {
  versionStr = fs.readFileSync(versionPath).toString() + '\n';
}

if(versionStr.indexOf(commit) != -1) {
  console.warn('\x1B[33m%s\x1b[0m', 'warming: 当前的git版本数据已经存在了!\n')
} else {
  let name = execSync('git show -s --format=%cn').toString().trim(); // 姓名
  let email = execSync('git show -s --format=%ce').toString().trim(); // 邮箱
  let date = new Date(execSync('git show -s --format=%cd').toString()); // 日期
  let message = execSync('git show -s --format=%s').toString().trim(); // 说明
  versionStr = `git:${commit}\n作者:${name}<${email}>\n日期:${date.getFullYear()+&#39;-&#39;+(date.getMonth()+1)+&#39;-&#39;+date.getDate()+&#39; &#39;+date.getHours()+&#39;:&#39;+date.getMinutes()}\n说明:${message}\n${new Array(80).join(&#39;*&#39;)}\n${versionStr}`;
  fs.writeFileSync(versionPath, versionStr);
  // 写入版本信息之后,自动将版本信息提交到当前分支的git上
  if(autoPush) { // 这一步可以按照实际的需求来编写
    execSync(`git add ${ versionPath }`);
    execSync(`git commit ${ versionPath } -m 自动提交版本信息`);
    execSync(`git push origin ${ execSync(&#39;git rev-parse --abbrev-ref HEAD&#39;).toString().trim() }`)
  }
}

if(fs.existsSync(buildPath)) {
  fs.writeFileSync(`${ buildPath }/${ versionPath }`, fs.readFileSync(versionPath))
}

上面的檔案可以直接透過

node commit.js 進行。為了方便管理,我們在package.json 上加上命令列:

"scripts": {
  "commit": "node commit.js"
}

那樣,使用

npm run commit 同等node commit.js 的效果。

產生版本資訊

有了上面的鋪墊,我們可以透過

commit 的訊息,產生指定格式的版本資訊version .json了。

在根目錄中新檔案

version.js用來產生版本的資料。

const execSync = require(&#39;child_process&#39;).execSync;
const fs = require(&#39;fs&#39;)
const targetFile = &#39;src/assets/version.json&#39;; // 存储到的目标文件

const commit = execSync(&#39;git show -s --format=%h&#39;).toString().trim(); //当前提交的版本号,hash 值的前7位
let date = new Date(execSync(&#39;git show -s --format=%cd&#39;).toString()); // 日期
let message = execSync(&#39;git show -s --format=%s&#39;).toString().trim(); // 说明

let versionObj = {
  "commit": commit,
  "date": date,
  "message": message
};

const data = JSON.stringify(versionObj);

fs.writeFile(targetFile, data, (err) => {
  if(err) {
    throw err
  }
  console.log(&#39;Stringify Json data is saved.&#39;)
})

我們在

package.json 上加上命令列方便管理:

"scripts": {
  "version": "node version.js"
}

根據環境產生版本資訊

針對不同的環境產生不同的版本訊息,假設我們這裡有開發環境

development,生產環境production 和車測試環境test

    生產環境版本資訊是
  • major.minor.patch,如:1.1.0
  • 開發環境版本資訊是
  • major.minor.patch :beta,如:1.1.0:beta
  • 測試環境版本資訊是
  • major.minor.path-data:hash,如:1.1.0-2022.01.01: 4rtr5rg
#方便管理不同環境,我們在專案的根目錄中新建檔案如下:

config
├── default.json          // 项目调用的配置文件
├── development.json      // 开发环境配置文件
├── production.json       // 生产环境配置文件
└── test.json             // 测试环境配置文件

相關的檔案內容如下:

// development.json
{
  "env": "development",
  "version": "1.3.0"
}
// production.json
{
  "env": "production",
  "version": "1.3.0"
}
// test.json
{
  "env": "test",
  "version": "1.3.0"
}

default .json 根據命令列拷貝不同環境的配置訊息,在package.json 中配置:

"scripts": {
  "copyConfigProduction": "cp ./config/production.json ./config/default.json",
  "copyConfigDevelopment": "cp ./config/development.json ./config/default.json",
  "copyConfigTest": "cp ./config/test.json ./config/default.json",
}

Is easy Bro, right?

整合

產生版本資訊的內容,得到根據不同環境產生不同的版本訊息,具體程式碼如下:

const execSync = require(&#39;child_process&#39;).execSync;
const fs = require(&#39;fs&#39;)
const targetFile = &#39;src/assets/version.json&#39;; // 存储到的目标文件
const config = require(&#39;./config/default.json&#39;);

const commit = execSync(&#39;git show -s --format=%h&#39;).toString().trim(); //当前提交的版本号
let date = new Date(execSync(&#39;git show -s --format=%cd&#39;).toString()); // 日期
let message = execSync(&#39;git show -s --format=%s&#39;).toString().trim(); // 说明

let versionObj = {
  "env": config.env,
  "version": "",
  "commit": commit,
  "date": date,
  "message": message
};

// 格式化日期
const formatDay = (date) => {
  let formatted_date = date.getFullYear() + "." + (date.getMonth()+1) + "." +date.getDate()
    return formatted_date;
}

if(config.env === &#39;production&#39;) {
  versionObj.version = config.version
}

if(config.env === &#39;development&#39;) {
  versionObj.version = `${ config.version }:beta`
}

if(config.env === &#39;test&#39;) {
  versionObj.version = `${ config.version }-${ formatDay(date) }:${ commit }`
}

const data = JSON.stringify(versionObj);

fs.writeFile(targetFile, data, (err) => {
  if(err) {
    throw err
  }
  console.log(&#39;Stringify Json data is saved.&#39;)
})

package.json 中添加不同環境的命令列:

"scripts": {
  "build:production": "npm run copyConfigProduction && npm run version",
  "build:development": "npm run copyConfigDevelopment && npm run version",
  "build:test": "npm run copyConfigTest && npm run version",
}

產生的版本資訊會直接存放在

assets 中,具體路徑為src/assets/version.json

結合 Angular 在頁面中展示版本信息

最後一步,在頁面中展示版本信息,這裡是跟

angular 結合。

使用

ng generate service versionapp/services 目錄中產生 version 服務。在生成的version.service.ts 檔案中新增請求訊息,如下:

import { Injectable } from &#39;@angular/core&#39;;
import { HttpClient } from &#39;@angular/common/http&#39;;
import { Observable } from &#39;rxjs&#39;;

@Injectable({
  providedIn: &#39;root&#39;
})
export class VersionService {

  constructor(
    private http: HttpClient
  ) { }

  public getVersion():Observable<any> {
    return this.http.get(&#39;assets/version.json&#39;)
  }
}

要使用請求之前,要在

app.module.ts 檔案掛載HttpClientModule 模組:

import { HttpClientModule } from &#39;@angular/common/http&#39;;

// ...

imports: [
  HttpClientModule
],

之後在元件中呼叫即可,這裡是

app.component.ts 檔案:

import { Component } from &#39;@angular/core&#39;;
import { VersionService } from &#39;./services/version.service&#39;; // 引入版本服务

@Component({
  selector: &#39;app-root&#39;,
  templateUrl: &#39;./app.component.html&#39;,
  styleUrls: [&#39;./app.component.less&#39;]
})
export class AppComponent {

  public version: string = &#39;1.0.0&#39;

  constructor(
    private readonly versionService: VersionService
  ) {}

  ngOnInit() {
    this.versionService.getVersion().subscribe({
      next: (data: any) => {
        this.version = data.version // 更改版本信息
      },
      error: (error: any) => {
        console.error(error)
      }
    })
  }
}

至此,我們完成了版本資訊。我們最後來調整下

package.json 的指令:

"scripts": {
  "start": "ng serve",
  "version": "node version.js",
  "commit": "node commit.js",
  "build": "ng build",
  "build:production": "npm run copyConfigProduction && npm run version && npm run build",
  "build:development": "npm run copyConfigDevelopment && npm run version && npm run build",
  "build:test": "npm run copyConfigTest && npm run version && npm run build",
  "copyConfigProduction": "cp ./config/production.json ./config/default.json",
  "copyConfigDevelopment": "cp ./config/development.json ./config/default.json",
  "copyConfigTest": "cp ./config/test.json ./config/default.json"
}

使用 scripts 一是为了方便管理,而是方便 jenkins 构建方便调用。对于 jenkins 部分,感兴趣者可以自行尝试。

更多编程相关知识,请访问:编程入门!!

以上是Angular怎麼結合Git Commit進行版本處理的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:掘金社区。如有侵權,請聯絡admin@php.cn刪除
JavaScript的演變:當前的趨勢和未來前景JavaScript的演變:當前的趨勢和未來前景Apr 10, 2025 am 09:33 AM

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

神秘的JavaScript:它的作用以及為什麼重要神秘的JavaScript:它的作用以及為什麼重要Apr 09, 2025 am 12:07 AM

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python還是JavaScript更好?Python還是JavaScript更好?Apr 06, 2025 am 12:14 AM

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

如何安裝JavaScript?如何安裝JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript不需要安裝,因為它已內置於現代瀏覽器中。你只需文本編輯器和瀏覽器即可開始使用。 1)在瀏覽器環境中,通過標籤嵌入HTML文件中運行。 2)在Node.js環境中,下載並安裝Node.js後,通過命令行運行JavaScript文件。

在Quartz中如何在任務開始前發送通知?在Quartz中如何在任務開始前發送通知?Apr 04, 2025 pm 09:24 PM

如何在Quartz中提前發送任務通知在使用Quartz定時器進行任務調度時,任務的執行時間是由cron表達式設定的。現�...

在JavaScript中,如何在構造函數中獲取原型鏈上函數的參數?在JavaScript中,如何在構造函數中獲取原型鏈上函數的參數?Apr 04, 2025 pm 09:21 PM

在JavaScript中如何獲取原型鏈上函數的參數在JavaScript編程中,理解和操作原型鏈上的函數參數是常見且重要的任�...

微信小程序webview中Vue.js動態style位移失效是什麼原因?微信小程序webview中Vue.js動態style位移失效是什麼原因?Apr 04, 2025 pm 09:18 PM

在微信小程序web-view中使用Vue.js動態style位移失效的原因分析在使用Vue.js...

在Tampermonkey中如何實現對多個鏈接的並發GET請求並依次判斷返回結果?在Tampermonkey中如何實現對多個鏈接的並發GET請求並依次判斷返回結果?Apr 04, 2025 pm 09:15 PM

在Tampermonkey中如何對多個鏈接進行並發GET請求並依次判斷返回結果?在Tampermonkey腳本中,我們經常需要對多個鏈...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器