返回
git获取代码的tag标号以及实现自动显示web版本
前端
2023-10-30 21:42:57
- 准备工作
1.1 安装依赖
npm install webpack git-rev
1.2 在 webpack 中配置 git-rev 插件
// webpack.config.js
const GitRevisionPlugin = require("git-rev");
module.exports = {
plugins: [
new GitRevisionPlugin()
]
};
2. 获取 tag 标号
2.1 获取 commit 标识
// app.js
import gitRevision from "git-rev";
console.log(gitRevision.tag()); // 输出当前 tag 标号
2.2 遍历所有 tag 文件
// app.js
import fs from "fs";
import path from "path";
const tagFiles = fs.readdirSync(path.join(__dirname, ".git/refs/tags"));
console.log(tagFiles); // 输出所有 tag 文件名
2.3 找到最大的 tag 标号
// app.js
import fs from "fs";
import path from "path";
const tagFiles = fs.readdirSync(path.join(__dirname, ".git/refs/tags"));
const tagNumbers = tagFiles.map((file) => parseInt(file.split("-")[1]));
console.log(Math.max(...tagNumbers)); // 输出最大的 tag 标号
3. 导出对象
// app.js
import fs from "fs";
import path from "path";
const tagFiles = fs.readdirSync(path.join(__dirname, ".git/refs/tags"));
const tagNumbers = tagFiles.map((file) => parseInt(file.split("-")[1]));
const maxTagNumber = Math.max(...tagNumbers);
export default {
tag: maxTagNumber
};
4. 在 web 版本中使用
在 web 版本中,我们可以通过导入导出对象来获取 tag 标号。
// index.js
import tagInfo from "./tagInfo.js";
console.log(tagInfo.tag); // 输出最大的 tag 标号
通过这种方法,我们可以在开发环境中自动获取和显示代码的 tag 标号,这可以方便我们追踪代码的版本变化。