webpack打包之后添加版本信息
因为目前开发的模式中存在,前端代码部署之后不能通过明显的标志判断是什么版本的。所以迫切的需要添加一个webpack打包的时候能够添加上项目的版本信息。所以才开始这个研究。
我实现的方式和参考地址的文章基本一致,只是最后的展现形式不一样。他是通过HtmlWwebpackPlugin插件将信息通过<%= %>方式输出在html文件中。我是将结果拿到之后放到window的下了。在浏览器控制台中输入window.BuildInfo就可以看到运行编译的信息。不用新创建一个html页面或者直接在控制台直接打印出来了。
实现代码:
- 在build目录下新建version.js文件中,编写以下代码:
const child_process = require('child_process')
// const readlineSync = require('readline-sync');
function getCommitDate (type) {
let DateObj = null
if (type == 'commit') {
DateObj = new Date(child_process.execSync(`git show -s --format=%cd`).toString())
} else if (type == 'build') {
DateObj = new Date()
}
let returnDate = `${DateObj.getFullYear() + '-' + (DateObj.getMonth() + 1) + '-' + DateObj.getDate() + ' ' + DateObj.getHours() + ':' + DateObj.getMinutes()}`
return returnDate
}
module.exports = function BuildInfo (env) {
let consoleInfo = {
commit: child_process.execSync('git show -s --format=%H').toString().trim(), // git最后一次提交
commitUserName: child_process.execSync('git show -s --format=%cn').toString().trim(), // 最后一次提交人
commitDate: getCommitDate('commit'), // 最后一次提交git时间
branch: child_process.execSync('git rev-parse --abbrev-ref HEAD').toString().trim(), // 当前代码所在分支
NODE_ENV: env
}
if (env == 'development') {
consoleInfo.runUserName = child_process.execSync('git config user.name').toString().trim() // 编译打包的人
consoleInfo.runFirstDate = getCommitDate('build')// 编译时间
} else if (env == 'production') {
// consoleInfo.testVersion = readlineSync.question('May I have you test version?') // 打包后提测的版本
consoleInfo.buildUserName = child_process.execSync('git config user.name').toString().trim() // 编译打包的人
consoleInfo.buildDate = getCommitDate('build') // 编译时间
}
return JSON.stringify(consoleInfo)
}
注意如果需要用到 readline-sync 功能的话,需要cnpm i readline-sync -S 进行下载依赖。
- 下config目录下的dev.env.js和prod.env.js进行引用
dev.env.js
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
const BuildInfo = require('../build/version.js')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
BUILD_INFO: BuildInfo('development')
})
prod.env.js
'use strict'
const BuildInfo = require('../build/version.js')
module.exports = {
NODE_ENV: '"production"',
BUILD_INFO: BuildInfo('production')
}
- 在main.js中使用
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
window.buildInfo = process.env.BUILD_INFO
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
- 最后效果
代码gitee地址: https://gitee.com/momobeizi/webpack-console-info.git

浙公网安备 33010602011771号