Webpack打包增加版本信息

838 阅读1分钟

痛点:现在前端项目几乎都是自动化打包,提供给部署方几乎都是打包后的代码,一旦项目间隔较久,或者分支版本很多,如果打包后的代码未带有版本信息,将很难追溯当前包的打包版本分支、打包人等信息。

解决方案

1、通过child_process获取git相对应的信息,新建version.js文件
const child_process = require("child_process");

// 分支名
const branchName = child_process.execSync("git rev-parse --abbrev-ref HEAD").toString().trim();

// 最后一次提交版本
const lastCommitVersion = child_process.execSync("git rev-parse HEAD").toString().trim();

// 最后一次提交者
const lastUser = child_process.execSync("git show -s --format=%cn").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 currentUser = child_process.execSync("git config user.name").toString().trim();

// 打包时间
const currentDateObj = new Date();
const currentDate = currentDateObj.getFullYear() + "-" + (currentDateObj.getMonth() + 1) + "-" + currentDateObj.getDate() + " " + currentDateObj.getHours() + ":" + currentDateObj.getMinutes();

module.exports = {
  branchName,
  lastCommitVersion,
  lastUser,
  commitDate,
  currentUser,
  currentDate
}
2、webpack.prod.js 引入
const BuildInfo = require("./version");
new HtmlWebpackPlugin({
    title: "版本信息",
    template: "src/version.ejs",
    filename: "static/version.html",
    inject: false,
    chunksSortMode: "none",
    buildInfo: BuildInfo
}),
3、vesion.ejs 模板
<!doctype html>
<html lang="zh-cn">

<head>
  <meta charset="utf-8">
  <title>版本声明</title>
  <meta name="viewport"
    content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
</head>

<body>
  <div id="root">
    <div>分支名:<%= htmlWebpackPlugin.options.buildInfo.branchName %></div>
    <div>最后一次提交版本:<%= htmlWebpackPlugin.options.buildInfo.lastCommitVersion %></div>
    <div>最后一次提交者:<%= htmlWebpackPlugin.options.buildInfo.lastUser %></div>
    <div>最后一次提交时间:<%= htmlWebpackPlugin.options.buildInfo.commitDate %></div>
    <div>当前打包的用户:<%= htmlWebpackPlugin.options.buildInfo.currentUser %></div>
    <div>打包时间:<%= htmlWebpackPlugin.options.buildInfo.currentDate %></div>
  </div>
</body>

</html>
4、打包后version.html文件即带有版本信息
参考文献:webpack 打包增加版本信息