編寫Webpack插件記錄build信息

背景

公司項目使用webpack+gitlab,打包發佈採用Jenkins自動化部署。天天都會發布多個版本,有時遇到問題須要知道前端包的版本信息。因爲項目是從零開始,並無此功能。
因此本文介紹如何編寫webpack插件,用於打包時自動記錄信息。姑且稱此插件爲RecordBuildInfoPlugin前端

How To Do

很簡單,只須要3步,便可實現。webpack

1. 編寫webpack插件文件

build文件夾下新建文件record-build-info-plugin.js,內容以下:git

const childProcess = require('child_process')
const os = require('os')
const fs = require('fs')

const VERSION_FILE_PATH = 'dist/static/build-info.json'

class RecordBuildInfoPlugin {
  constructor () {
    this.buildInfo = this.getBuildInfo()
  }

  getBuildInfo () {
    const commit = childProcess.execSync('git show -s --format=%H').toString().trim()
    const commitDateObj = new Date(childProcess.execSync(`git show -s --format=%cd`).toString())
    const commitDateTime = commitDateObj.toLocaleDateString() + ' ' + commitDateObj.toLocaleTimeString()
    const now = new Date()
    const buildDateTime = now.toLocaleDateString() + ' ' + now.toLocaleTimeString()
    const ipAddress = getIPAddress()
    return {
      commit, commitDateTime, buildDateTime, ipAddress
    }
  }

  saveBuildInfo () {
    fs.writeFileSync(VERSION_FILE_PATH, JSON.stringify(this.buildInfo))
  }

  apply (compiler) {
    if (compiler && compiler.hooks && compiler.hooks.done && compiler.hooks.done.tap) {
      // webpack 4.x
      compiler.hooks.done.tap('RecordBuildInfoPlugin', () => {
        this.saveBuildInfo()
      })
    } else if (compiler && compiler.plugin) {
      // webpack 3.x
      compiler.plugin('done', () => {
        this.saveBuildInfo()
      })
    } else {
      console.error('RecordBuildInfoPlugin Error')
    }
  }
}

function getIPAddress () {
  var interfaces = os.networkInterfaces()
  let ipArr = []
  for (let devName in interfaces) {
    let iface = interfaces[devName]
    for (let i = 0; i < iface.length; i++) {
      let alias = iface[i]
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        ipArr.push(alias.address)
      }
    }
  }
  return (ipArr.length ? ipArr : 'Fail Get IP')
}

module.exports = RecordBuildInfoPlugin

2. 在webpack.prod.conf.js文件中引用這個plugin

const RecordBuildInfoPlugin = require('./record-build-info-plugin')
const webpackConfig = merge(baseWebpackConfig, {
  plugins: [
    // 在末尾處引用
    new RecordBuildInfoPlugin()
  ]
})

3. 最後驗證

npm run build

dist/static下會多出json文件,記錄打包信息。web

總結

  • webpack的插件,就是新建一個class,引用後webpack會調用此類的apply方法,在apply方法中去實現本身想作的事情。
  • 本文只是拋磚引玉,除了代碼裏記錄的各類信息外,還能夠幹不少事情。但願看完本文後,你能夠快速地完成本身的webpack plugin。
相關文章
相關標籤/搜索