git項目中加入版本號git-revision-webpack-plugin


如何在git項目中加入版本號和代碼提交等信息,其實安裝一個插件( git-revision-webpack-plugin)再加一些配置就搞定,具體操作如下: 

安裝本地開發依賴項

Webpack 4及以上版本:

cnpm install --save-dev git-revision-webpack-plugin

 

Webpack 4以下版本:

cnpm install --save-dev git-revision-webpack-plugin@2.5.1

插件API

VERSIONCOMMITHASH並且BRANCH也通過一個公共的API暴露。使用DefinePlugin的示例:

(這里以react項目為例:打開本地環境:build/webpack.config.dev.js 或 開發環境:build/webpack.config.prod.js)

const BuildInfo = require('./version.js');  // 定制一些其他信息,如不需要可不引入 const GitRevisionPlugin = require('git-revision-webpack-plugin'); const gitRevision = new GitRevisionPlugin(); plugins: [ gitRevision, new webpack.DefinePlugin({ 'process.env': { 'VERSION': JSON.stringify(gitRevision.version()), 'COMMITHASH': JSON.stringify(gitRevision.commithash()), 'BRANCH': JSON.stringify(gitRevision.branch()), 'BuildDate': JSON.stringify(BuildInfo.buildDate)  // 后面這些可以根據自己的實際需求進行添加
.
.
.
           }
 }) ],  

 

version.js 配置文件
const child_process = require('child_process');

// git 最后一次提交的 Head
const commit = child_process
    .execSync('git show -s --format=%H')
    .toString()
    .trim();
const commitUserName = child_process
    .execSync('git show -s --format=%cn')
    .toString()
    .trim();
const commitUserMail = child_process
    .execSync('git show -s --format=%ce')
    .toString()
    .trim();
const commitDateObj = new Date(child_process.execSync(`git show -s --format=%cd`).toString());
const commitDate = `${commitDateObj.getFullYear() +
    '-' +
    (commitDateObj.getMonth() + 1) +
    '-' +
    commitDateObj.getDate() +
    ' ' +
    commitDateObj.getHours() +
    ':' +
    commitDateObj.getMinutes()}`;
const buildUserName = child_process
    .execSync('git config user.name')
    .toString()
    .trim();
const buildUserMail = child_process
    .execSync('git config user.email')
    .toString()
    .trim();
const nowDate = new Date();
const buildDate = `${nowDate.getFullYear() +
    '-' +
    (nowDate.getMonth() + 1) +
    '-' +
    nowDate.getDate() +
    ' ' +
    nowDate.getHours() +
    ':' +
    nowDate.getMinutes()}`;

module.exports = { commit, commitUserName, commitUserMail, commitDate, buildUserName, buildUserMail, buildDate };

 

使用

在頁面中可以直接使用process.env.xxx方法顯示,如下:

<div id="version">
      <p>COMMITHASH:{process.env.VERSION}</p>
      <p>BRANCH:{process.env.BRANCH}</p>
      <p>VERSION:{process.env.VERSION}</p>
      <p>Build Date:{process.env.BUILDDATE}</p>
</div>   
COMMITHASH: e3caffa36e4062cebe657c35b70ef198fa77d90a
BRANCH: release
VERSION: e3caffa
Build Date: 2020-10-26 8:47

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM