欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

webpack打包生成git commit的版本信息(只需三步)

程序员文章站 2022-06-24 16:37:29
webpack打包生成git commit的版本信息1. 项目根目录下创建version.js文件version.js文件(与webpack.config.js文件同级)内容如下:2. src目录下创建version/index.html文件version/index.html内容如下:3. webpack.prod.config.js文件增加以下内容:1. 项目根目录下创建version.js文件version.js文件(与webpack.config.js文件同级)内容如下:const child...

1. 项目根目录下创建version.js文件

version.js文件(与webpack.config.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 }

2. src目录下创建version/index.html文件

version/index.html内容如下:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1,IE=11,IE=10">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes" />
    <title>版本声明</title>
</head>

<body>
    <p>commit: <%= htmlWebpackPlugin.options.buildInfo.commit %></p>
    <p>commitUserName: <%= htmlWebpackPlugin.options.buildInfo.commitUserName %></p>
    <p>commitDate: <%= htmlWebpackPlugin.options.buildInfo.commitDate %></p>
    <p>buildUserName: <%= htmlWebpackPlugin.options.buildInfo.buildUserName %></p>
    <p>buildUserMail: <%= htmlWebpackPlugin.options.buildInfo.buildUserMail %></p>
    <p>buildDate: <%= htmlWebpackPlugin.options.buildInfo.buildDate %></p>
</body>

</html>

3. webpack.prod.config.js文件增加以下内容:

const BuildInfo = require('./version.js')

 new HtmlWebpackPlugin({
      filename: './staticsRoot/version.html',  //打包后生成的文件路径
      template: './src/version/index.html',  //需要处理的对象
      inject: false,//不插入生成的js 仅用于版本声明
      minify: {
        removeComments: false,
        collapseWhitespace: true,
        removeAttributeQuotes: true
      },
      buildInfo: BuildInfo
    }),

大功告成!此时运行npm run build命令,将会生成dist/staticsRoot/version.html文件,此文件即为git版本信息详情。

本文地址:https://blog.csdn.net/qq_36894992/article/details/111031154