What do we need?
笔者目的是在vue项目打包后的 dist/index.html 文件中写入本次打包git用户、最后一次git提交信息,这样做的目的是便于线上项目的管理和防止同事之间的相互扯皮。
最后打包出的效果如下图:
How to do?
版本信息需要记录 git最后一次提交作者(作者名和邮箱邮)、日期、commit HEAD,本次打包git用户和邮箱、日期,这些信息都需要使用 git 命令来获取到。在 node 中,要执行一段命令行脚步需要使用 child_process 模块。
项目 build 目录下新建 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}
在 webpack.prod.conf.js 文件中引入 version.js 模块,并修改 HtmlWebpackPlugin 插件的配置。const BuildInfo = require('./version.js')
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: false, // index.html 保留注释
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency',
buildInfo: JSON.stringify(BuildInfo)
}),
接着在 index.html 文件内容开头添加 版本信息注释。
html>
至此大功告成!!!
suggest up-and-coming youngster
同事提议可将版本信息从 index.html 抽出来搞个 version.html,他是这样实现的:
1、项目根目录下新建 version\index.html 文件html>
content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes" />
版本声明commit:
commitUserName:
commitDate:
buildUserName:
buildUserMail:
buildDate:
2、 webpack.prod.conf.js 文件中新增一个 HtmlWebpackPlugin 配置项new HtmlWebpackPlugin({
filename: './static/version.html',
template: 'version/index.html',
inject: false,//不插入生成的js 仅用于版本声明
minify: {
removeComments: false,
collapseWhitespace: true,
removeAttributeQuotes: true
},
buildInfo: BuildInfo
}),
这样打包后会生成 dist\static\version.html ,成功将 版本信息和index.html 文件分离。