
如何快速入門VUE3.0:進入學習

上圖是頁面上展示的测试环境/开发环境版本資訊。 【相關教學推薦:《angular教學》】
後面有介紹

上圖表示的是每次提交的Git Commit的信息,當然,這裡我是每次提交都記錄,你可以在每次構建的時候記錄。
So,我們接下來用Angular實現下效果, React和Vue同理。
因為這裡的重點不是搭建環境,我們直接用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%sx1b[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()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes()}n說明:${message}n${new Array(80).join('*')}n${versionStr}`;
fs.writeFileSync(versionPath, versionStr);
// 寫入版本資訊之後,自動將版本資訊提交到目前分支的git上if(autoPush) { // 這一步可以依照實際的需求來寫execSync(`git add ${ versionPath }`);
execSync(`git commit ${ versionPath } -m 自動提交版本資訊`);
execSync(`git push origin ${ execSync('git rev-parse --abbrev-ref HEAD').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('child_process').execSync;
const fs = require('fs')
const targetFile = 'src/assets/version.json'; // 儲存到的目標檔案const commit = execSync('git show -s --format=%h').toString().trim(); //目前提交的版本號,hash 值的前7位元let date = new Date(execSync('git show -s --format=%cd').toString()); // 日期let message = execSync('git show - s --format=%s').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('Stringify Json data is saved.')
})我們在package.json上加上命令列方便管理:
"scripts": {
"version": "node version.js"
}針對不同的環境產生不同的版本信息,假設我們這裡有開發環境development ,生產環境production和車測試環境test 。
major.minor.patch ,如:1.1.0major.minor.patch:beta ,如:1.1.0:betamajor.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('child_process').execSync;
const fs = require('fs')
const targetFile = 'src/assets/version.json'; // 儲存到的目標檔案const config = require('./config/default.json');
const commit = execSync('git show -s --format=%h').toString().trim(); //目前提交的版本號let date = new Date(execSync('git show -s --format =%cd').toString()); // 日期let message = execSync('git show -s --format=%s').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 === 'production') {
versionObj.version = config.version
}
if(config.env === 'development') {
versionObj.version = `${ config.version }:beta`
}
if(config.env === 'test') {
versionObj.version = `${ config.version }-${ formatDay(date) }:${ commit }`
}
const data = JSON.stringify(versionObj);
fs.writeFile(targetFile, data, (err) => {
if(err) {
throw err
}
console.log('Stringify Json data is saved.')
})在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結合。
使用ng generate service version在app/services目錄中產生version服務。在產生的version.service.ts檔案中加入請求訊息,如下:
import { Injectable } from '@angular/core';
import { HttpClient } 從 '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class VersionService {
constructor(
private http: HttpClient
) { }
public getVersion():Observable<any> {
return this.http.get('assets/version.json')
}
}要使用請求之前,要在app.module.ts檔案掛載HttpClientModule模組:
import { HttpClientModule } from '@angular/common/http';
// ...
imports: [
HttpClientModule
],之後在元件中呼叫即可,這裡是app.component.ts檔:
import { Component } from '@angular/core';
import { VersionService } from './services/version.service'; // 引入版本服務@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
public version: string = '1.0.0'
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部分,有興趣者可以自行嘗試。