1. 程式人生 > 其它 >webpack打包之後新增版本資訊

webpack打包之後新增版本資訊

因為目前開發的模式中存在,前端程式碼部署之後不能通過明顯的標誌判斷是什麼版本的。所以迫切的需要新增一個webpack打包的時候能夠新增上專案的版本資訊。所以才開始這個研究。

參考地址

我實現的方式和參考地址的文章基本一致,只是最後的展現形式不一樣。他是通過HtmlWwebpackPlugin外掛將資訊通過<%= %>方式輸出在html檔案中。我是將結果拿到之後放到window的下了。在瀏覽器控制檯中輸入window.BuildInfo就可以看到執行編譯的資訊。不用新建立一個html頁面或者直接在控制檯直接打印出來了。

實現程式碼:

  1. 在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 進行下載依賴。

  1. 下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')
}
  1. 在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/>'
})
  1. 最後效果

程式碼gitee地址: https://gitee.com/momobeizi/webpack-console-info.git